[中序遍历]leetcode501:二叉搜索树中的众数(easy)

题目:
在这里插入图片描述
题解:

  • 思路:二叉搜索树的中序遍历是一个升序序列,逐个比对当前结点(root)值与前驱结点(pre)值。更新当前节点值出现次数(curTimes,初始化为1)及最大出现次数(maxTimes),更新规则:若curTimes=maxTimes,将root->val添加到结果向量(res)中;若curTimes>maxTimes,清空res,将root->val添加到res,并更新maxTimes为curTimes。

代码如下:

class Solution {
public:
   //思路:二叉搜索树的中序遍历是一个升序序列,逐个比对当前结点(root)值与前驱结点(pre)值。更新当前节点值出现次数(curTimes)及最大出现次数(maxTimes),更新规则:若curTimes=maxTimes,将root->val添加到结果向量(res)中;若curTimes>maxTimes,清空res,将root->val添加到res,并更新maxTimes为curTimes。
    vector<int> findMode(TreeNode* root) {
        if(!root)return {};
        vector<int> res;
        //最大次数初始化为1,当前root节点值的次数初始化为1
        int maxTimes=0,curTimes=1;
        TreeNode* pre=nullptr;
        dfs(root,pre,curTimes,maxTimes,res);
        return res;
    }

    
    void dfs(TreeNode* &root,TreeNode* &pre,int& curTimes,int& maxTimes,vector<int>& res){
        if(!root)return;
        dfs(root->left,pre,curTimes,maxTimes,res);
        if(pre){
            curTimes=(root->val==pre->val)?curTimes+1:1;
        }
        if(curTimes==maxTimes){//当前节点的次数等于最大次数,添加到res中
            res.push_back(root->val);
        }
        else if(curTimes>maxTimes){//当前节点的次数大于最大次数,清空res,然后将当前节点值添加res中,更新最大次数为当前节点的最大次数
            res.clear();
            res.push_back(root->val);
            maxTimes=curTimes;
        }
        pre=root;
        dfs(root->right,pre,curTimes,maxTimes,res);
    }
};
发布了484 篇原创文章 · 获赞 149 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/qq_43152052/article/details/103896942