zoukankan      html  css  js  c++  java
  • 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;
        }
    };
    
    作者:LightAc
    出处:https://www.cnblogs.com/lightac/
    联系:
    Email: dzz@stu.ouc.edu.cn
    QQ: 1171613053
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
  • 相关阅读:
    Expanding Rods(二分)
    Monthly Expense(二分)
    sdut1269 走迷宫(dfs)
    走迷宫(dfs)
    C Looooops(扩展欧几里得+模线性方程)
    41. First Missing Positive
    40. Combination Sum II
    39. Combination Sum
    37. Sudoku Solver
    36. Valid Sudoku
  • 原文地址:https://www.cnblogs.com/lightac/p/13724411.html
Copyright © 2011-2022 走看看