[ 二叉树 ] 二叉搜索树中的众数

501. 二叉搜索树中的众数 - 力扣(LeetCode) (leetcode-cn.com)

二叉搜索树中的众数

递归

  • 该非严格意义上的二叉搜索树的**中序遍历结果是不严格递增**的
  • 保存上次访问指针
class Solution {
public:
    int maxCount;
    int count;
    TreeNode* pre;
    vector<int> ans;
    void searchBST(TreeNode* cur) {
        if (!cur) return;
        // 左
        searchBST(cur->left);
        
        // 中
        // 如果是第一个结点,没有前驱,频率为1
        if (!pre) count = 1;

        // 如果当前结点值等于前驱结点 频率++
        else if (pre->val == cur->val) count++;

        // 否则刷新频率
        else count = 1;

        // 记录前驱结点
        pre = cur;

        // 判断是否刷新最大频率
        if (count == maxCount) ans.emplace_back(cur->val);
        else if (count > maxCount) {
            maxCount = count;
            ans.clear();
            ans.emplace_back(cur->val);
        }

        // 右
        searchBST(cur->right);
        return;
    }
    
    vector<int> findMode(TreeNode* root) {
        searchBST(root);
        return ans;
    }
};

非递归

  • 该非严格意义上的二叉搜索树的**中序遍历结果是不严格递增**的
  • 保存上次访问指针
class Solution {
public:
    vector<int> findMode(TreeNode* root) {
        vector<int> ans;
        // 保存前驱结点
        TreeNode* pre = nullptr;
        
        // 频率
        int count = 0;
        int maxCount = 0;

        stack<TreeNode*> stk;
        if (root) stk.push(root);
        while (!stk.empty()) {
            TreeNode* node = stk.top();
            stk.pop();
            if (node) {
                if (node->right) stk.push(node->right);
                stk.push(node);
                stk.push(nullptr);
                if (node->left) stk.push(node->left);
            }
            // 仅需要处理结点, 处理方式同递归方法一致
            else {
                node = stk.top();
                stk.pop();
                if (!pre) count = 1;
                else if (pre->val == node->val) count++;
                else count = 1;
                pre = node;
                if(count == maxCount) ans.emplace_back(node->val);
                else if (count > maxCount) {
                    maxCount = count;
                    ans.clear();
                    ans.emplace_back(node->val);
                }
            }
        }
        return ans;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值