【代码随想录day 18】 力扣 501.二叉搜索树中的众数

发布于:2025-08-13 ⋅ 阅读:(14) ⋅ 点赞:(0)

视频讲解:https://www.bilibili.com/video/BV1fD4y117gp/?vd_source=a935eaede74a204ec74fd041b917810c
文档讲解:https://programmercarl.com/0501.%E4%BA%8C%E5%8F%89%E6%90%9C%E7%B4%A2%E6%A0%91%E4%B8%AD%E7%9A%84%E4%BC%97%E6%95%B0.html#%E6%80%9D%E8%B7%AF
力扣题目:https://leetcode.cn/problems/find-mode-in-binary-search-tree/

这道题的主要思路如下:

  1. 双指针遍历二叉树,在遍历过程中对遍历的数进行如下操作。
  2. 如果pre指针等于cur指针,count++,如果不相等,count重新计数,pre指针始终跟紧cur指针。
  3. 如果count大于maxcount,更新maxcount,并且把存入数组的数弹出放入新的。
class Solution {
public:
    TreeNode *pre=NULL;
    int count=0;
    int maxcount=0;
    vector<int> result;
    void travesal(TreeNode *cur)
    {
        //判断终止条件
        if(cur == NULL) return;
        //开始递归
        //左
        travesal(cur->left);
        //中
        //第一次遍历,pre还没跟上cur,count计数为1
        if(pre == NULL) count=1;
        //pre跟上了cur,即pre有值,且等于cur的值,count计数++
        else if(pre->val==cur->val) count++;
        //pre存在且不相等与cur,重新计数count
        else count=1;
        //pre跟上cur
        pre=cur;
        //如果count等于maxcount,即众数不止一个,存入数组中
        if(count == maxcount)  result.push_back(cur->val);
        //如果count大于最大count,更新maxcount
        if(count>maxcount) 
        {
            maxcount=count;
            //说明有其他数的频率大于这个数,弹出并放入新的数
            result.clear();
            result.push_back(cur->val);

        }
        //右
        travesal(cur->right);
        return;
    }
    vector<int> findMode(TreeNode* root) {
        //if(!root) return 0;
        travesal(root);
        return result;
    }
};