Simple C++ Solution using Inorder traversal without extra space


  • 1
    S

    '''

    class Solution {
        int count = 0;
        int maxCount = 0;
        int currentVal;
    public:
        void preOrderTraversal(TreeNode* root, vector<int> &modes){
            if(root == nullptr){
                return;
            }
            preOrderTraversal(root->left, modes);
            
            if(currentVal == root->val){
                count += 1;
            }else{
                currentVal = root->val;
                count = 1;
            }
            if(count > maxCount){
                modes.clear();
                maxCount = count;
                modes.push_back(currentVal);
            }else if(count == maxCount){
                modes.push_back(currentVal);
            }
            
            preOrderTraversal(root->right, modes);
            
            return;
        }
        
        vector<int> findMode(TreeNode* root) {
            vector<int> modes;
            preOrderTraversal(root, modes);
            return modes;
        }
    };
    

    '''


  • 0
    S

    I think the code is easy to follow but please leave a comment if anyone needs detailed explanation.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.