LeetCode 501. Find Mode in Binary Search Tree(寻找二叉查找树中出现次数最多的值)

题意:寻找二叉查找树中出现次数最多的值

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int ma = 0;
    int cnt = 1;
    TreeNode *pre = NULL;
    vector<int> ans;
    void inorder(TreeNode* root){
        if(root == NULL) return;
        inorder(root -> left);
        if(pre){
            if(pre -> val == root -> val){
                ++cnt;   
            }
            else{
                if(cnt > ma){
                    ma = cnt;
                    ans.clear();
                    ans.push_back(pre -> val);
                }
                else if(cnt == ma){
                    ans.push_back(pre -> val);
                }
                cnt = 1;
            }
        } 
        pre = root;
        inorder(root -> right);
    }
    vector<int> findMode(TreeNode* root) {
        if(root == NULL) return ans;
        inorder(root);
        if(cnt > ma){
            ans.clear();
            ans.push_back(pre -> val);
        }
        else if(cnt == ma){
            ans.push_back(pre -> val);
        }
        return ans;
    }
};

 

posted @ 2020-04-01 00:02  Somnuspoppy  阅读(208)  评论(0编辑  收藏  举报