【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);
    }
};

  

上一篇:LeetCode题解之 Increasing Order Search Tree


下一篇:[Lintcode]73. Construct Binary Tree from Preorder and Inorder Traversal/[Leetcode]