501. 二叉搜索树中的众数

Q:

在这里插入图片描述

A:

首先这题可以遍历一遍二叉树,用一个map来存每个数字出现的次数之后取最大的就行,但这样没有利用到二叉搜索树的条件。所以我们利用二叉搜索树中序遍历升序(此题中为非降序)的性质,保存中序前缀节点,若当前节点与前缀节点值相同,计数+1,若不同则重新从0开始计数。因为是非降序,所以一旦遍历到了一个更大的数字,之后的数字都只会相同或更大。额外维持一个全局变量maxsize记录目前为止的出现最多数字的出现次数,视情况更新maxsize和结果数组。

迭代版:
/**
 * 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> findMode(TreeNode* root) {
        if(root==0){
            return vector<int>();
        }
        vector<int> res;
        stack<TreeNode*> sta;
        TreeNode* cur=root,*pre_cur=0;
        int cur_size=0,max_size=0;
        while(cur or !sta.empty()){
            if(cur){
                sta.push(cur);
                cur=cur->left;
            }
            else{
                cur=sta.top();
                sta.pop();
                if(pre_cur and cur->val==pre_cur->val){
                    cur_size++;
                }
                else{
                    cur_size=1;
                }
                if(cur_size>max_size){
                    max_size=cur_size;
                    res.clear();
                    res.push_back(cur->val);
                }
                else if(cur_size==max_size){
                    res.push_back(cur->val);
                }
                pre_cur=cur;
                cur=cur->right;
            }
        }
        return res;
    }
};
递归版
/**
 * 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> findMode(TreeNode* root) {
        if(root==0){
            return vector<int>();
        }
        int maxsize=0,cursize=0;
        vector<int> res;
        TreeNode* pre_root=0;
        helper(root,res,maxsize,cursize,pre_root);
        return res;
    }
    void helper(TreeNode* root,vector<int>& res,int& maxsize,int& cursize,TreeNode*& pre_root){//中序遍历
        if(root->left){
            helper(root->left,res,maxsize,cursize,pre_root);
        }
        if(pre_root and pre_root->val==root->val){
            ++cursize;
        }
        else{
            cursize=1;
        }
        if(cursize>maxsize){
            maxsize=cursize;
            res.clear();
            res.push_back(root->val);
        }
        else if(cursize==maxsize){
            res.push_back(root->val);
        }
        pre_root=root;
        if(root->right){
            helper(root->right,res,maxsize,cursize,pre_root);
        }

    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值