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
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
  • 相关阅读:
    docker将jar打包镜像文件
    特性阻抗(转)
    关于三极管偏置电路的思考
    怎样理解阻抗匹配?(转)
    你要包火到几时呢
    Bluetooth Note
    今年过年没回家
    第二天(tomcat与web程序结构与Http协议与HttpUrlConnection)
    JavaIO操作(1)转换流
    canphp框架功能与特性介绍
  • 原文地址:https://www.cnblogs.com/lightac/p/13724411.html
Copyright © 2011-2022 走看看