C++ O(1) space solution


  • 0
    A

    For explanation, please see the following post:

    Proper O(1) space

    class Solution {
    public:
        void helper(TreeNode *root, vector<int> &ans, int &maxCount, int &curCount, int &curVal, bool isSecondPass) {
            if (!root)
                return;
            
            helper(root->left, ans, maxCount, curCount, curVal, isSecondPass);
            
            if (!curCount || root->val != curVal) {
                curVal = root->val;
                curCount = 0;
            }
            ++curCount;
            
            if (curCount == maxCount) {
                if (isSecondPass)
                    ans.push_back(curVal);
            }
            else if (curCount > maxCount)
                maxCount = curCount;
            
            helper(root->right, ans, maxCount, curCount, curVal, isSecondPass);
        }
    
        vector<int> findMode(TreeNode* root) {
            vector<int> ans;
            int maxCount = 0, curCount = 0, curVal;
            helper(root, ans, maxCount, curCount, curVal, false);
            curCount = 0;
            helper(root, ans, maxCount, curCount, curVal, true);
            return ans;
        }
    };
    

Log in to reply
 

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