【leetcode】501. Find Mode in Binary Search Tree

class Solution {
public:
    vector<int> modes;
    int maxCnt = 0;
    int curCnt = 0;
    int curNum = 0;
    vector<int> findMode(TreeNode* root) {
       if (!root) {
          return modes;
       }

       curNum = root->val; 
       inOrder(root);
        
       return modes;
    }
    
    void inOrder(TreeNode* root) {
        if (!root) {
            return;
        }
        
        inOrder(root->left);
        
        if (root->val == curNum) {
            curCnt++;
        } else {
            curCnt = 1;
            curNum = root->val;
        }
        
        if (curCnt > maxCnt) {
            // clear all number that have less occurred times
            modes = {};
            modes.push_back(curNum);
            maxCnt = curCnt;
        } else if (curCnt == maxCnt) {
            modes.push_back(curNum);
        }  

        inOrder(root->right);
    }
};

  

posted @ 2019-02-15 16:56  南岛的森林  阅读(94)  评论(0编辑  收藏  举报