leetcode501. 二叉搜索树中的众数

本文介绍了两种解决LeetCode 501题目的方法:一种是深度优先搜索结合映射统计,另一种是利用中序遍历特性。这两种方法分别分析了其思路和优缺点,其中中序遍历的方法更符合题目进阶要求,不使用额外空间。通过遍历二叉搜索树,可以有效地找到出现频率最高的元素,即众数。
摘要由CSDN通过智能技术生成

题目:501. 二叉搜索树中的众数

给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素)。

假定 BST 有如下定义:

  • 结点左子树中所含结点的值小于等于当前结点的值
  • 结点右子树中所含结点的值大于等于当前结点的值
  • 左子树和右子树都是二叉搜索树
例如:
给定 BST [1,null,2,2],

   1
    \
     2
    /
   2
返回[2].

提示: 如果众数超过1个,不需考虑输出顺序

进阶: 你可以不使用额外的空间吗?(假设由递归产生的隐式调用栈的开销不被计算在内)

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-mode-in-binary-search-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

基本思想1:dfs+map统计次数

空间复杂度不满足进阶的要求,并且未用上该树是二叉搜索树这个特征。

/**
 * 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:
    unordered_map<int, int> m;
    vector<int> findMode(TreeNode* root) {
        preorder(root);
        vector<int> res;
        int cnt = 0;
        for(auto t : m){
            if(t.second > cnt){
                res.clear();
                res.push_back(t.first);
                cnt = t.second;
            }
            else if(t.second == cnt){
                res.push_back(t.first);
            }
        }
        return res;
    }
    void preorder(TreeNode* root){
        if(root){
            m[root->val]++;
            preorder(root->left);
            preorder(root->right);
        }
    }
};

基本思想2:中序遍历

  • 以中序的形式遍历该二叉树,使得大小相等的元素,遍历的先后顺序紧挨着
  • 遍历到该元素时,统计出现的次数,并判断是否和目前之前元素出现的最大次数的关系

特别注意一点:在写递归的中序遍历程序时,要将之前出现的元素以及之前元素出现的次数设为引用类型,因为这两个变量要时时更新,而不是要维护当时调用该函数时这两个变量的值。

/**
 * 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:
    vector<int> res;
    int max_cnt = 0;
    vector<int> findMode(TreeNode* root) {
        int cnt = 0, pre = INT_MIN;
        inorder(root, cnt, pre);        
        return res;
    }
    void inorder(TreeNode* root, int &cnt, int &pre){
        if(root){
            inorder(root->left, cnt, pre);

            if(root->val == pre){
                ++cnt;                
            }
            else{
                cnt = 1;
            }
            
            if(cnt > max_cnt){
                max_cnt = cnt;
                res.clear(); 
                res.push_back(root->val);               
            }
            else if(cnt == max_cnt){
                res.push_back(root->val);
            }
            pre = root->val;

            inorder(root->right, cnt, pre);
        }
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值