C++ Morris need to simplify somehow...


  • 0
    class Solution {
        vector<int> result;
    public:
        void helper(int num, int& Mnum, int& maxcnt, int &cnt)
        {
            if(num!=Mnum)
                cnt=0;
            cnt++;
            Mnum=num;
            if(maxcnt<cnt)
            {
                result.clear();
                result.push_back(num);
                maxcnt=cnt;
            }
            else if(maxcnt==cnt)
                result.push_back(num);
        }
        vector<int> findMode(TreeNode* root) {
            if(!root) return result;
            TreeNode* cur = root;
            TreeNode* pre;
            int Mnum=INT_MIN, maxcnt=0, cnt=0; 
            while(cur)
            {
                pre=cur->left;
                if(pre)
                {
                    while(pre->right && pre->right!=cur)
                        pre=pre->right;
                    if(!pre->right)
                    {
                        pre->right=cur;
                        cur=cur->left;
                    }
                    else
                    {
                        helper(cur->val, Mnum, maxcnt, cnt);//
                        cur=cur->right;
                        pre->right=NULL;
                    }
                }
                else
                {
                    helper(cur->val, Mnum, maxcnt, cnt);//
                    cur=cur->right;
                }
            }
            return result;
        }
    };
    

Log in to reply
 

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