2020年9月24日LC打卡

 

 对二叉树进行中序遍历,用maxCount记录最大值。如果存在count==maxCount,压进vector之中。如果count更大,更新vector。

/**
 * 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 count;
    int maxCount;
    TreeNode* pre;
    vector<int> ans;
    void searchBST(TreeNode* cur) {
        if(cur == NULL){
            return;
        }
        searchBST(cur->left);
        if(pre == NULL) {
            count = 1;
        }
        else if (pre->val == cur->val){
            count++;
        }
        else {
            count = 1;
        }
        pre = cur;
        if(count == maxCount) {
            ans.push_back(cur->val);
        }
        if(count > maxCount) {
            maxCount = count;
            ans.clear();
            ans.push_back(cur->val);
        }
        searchBST(cur->right);
        return;
    }
    vector<int> findMode(TreeNode* root) {
        int count = 0;
        int maxCount = 0;
        TreeNode* pre = NULL;
        ans.clear();
        searchBST(root);
        return ans;
    }
};

 

posted @ 2020-09-24 15:44  LightAc  阅读(157)  评论(0编辑  收藏  举报
返回顶端