代码随想录之二叉搜索树中的众数

本题在力扣501

本题的解法学习于代码随想录
思路:二叉搜索树相关的算法题要使用到二叉搜索树的特性,本题的难点是如何将出现相同次数的众数保存起来,以及count条件的转换。

JAVA版本:

解法一:使用递归的方法来完成

class Solution {
            //先定义需要的变量
        int count =0;       //次数
        int maxCount =0;    //最大值
        TreeNode pre = null;//前一个结点
        ArrayList<Integer> resList = new ArrayList<>();//定义存储众数的数组
    public int[] findMode(TreeNode root) {
        checkNum(root); //定义递归函数
        int[] res = new int[resList.size()];
        for (int i = 0; i < resList.size(); i++) {
            res[i] = resList.get(i);
        }
        return res;

    }

    public void checkNum(TreeNode root){
        if(root ==null) {
            return;
        }
        //使用二叉排序树的特性来进行中序遍历

        checkNum(root.left);
        int rootValue = root.val;

        //**注意查找到相关众数的条件 */
        if(pre ==null || rootValue != pre.val){
            //root结点的值跟pre结点的值来比较,利用二叉排序树的特性
            count =1;
        }else{
            count++;
        }

        //更新最新的结果
        if(count > maxCount){
            resList.clear(); //**清空数组很重要 */
            resList.add(rootValue);
            maxCount = count;
        }else if (count == maxCount){ //解决出现了多个相同次数众数的问题
        resList.add(rootValue); 
        }
        pre = root;

        checkNum(root.right);
    }
}

解法二:使用迭代的方式,二叉树的中序遍历

class Solution {
    public int[] findMode(TreeNode root) {
        TreeNode pre = null;
        Stack<TreeNode> stack = new Stack<>();
        List<Integer> result = new ArrayList<>();
        int maxCount = 0;
        int count = 0;
        TreeNode cur = root;
        while(cur !=null ||!stack.isEmpty()) {
            if (cur != null) {
                stack.push(cur);
                cur =cur.left;
            }else {
                cur = stack.pop();
                // 计数
                if (pre == null || cur.val != pre.val) {
                    count = 1;
                }else {
                    count++;
                }
                // 更新结果
                if (count > maxCount) {
                    maxCount = count;
                    result.clear();
                    result.add(cur.val);
                }else if (count == maxCount) {
                    result.add(cur.val);
                }
                pre = cur;
                cur = cur.right;
        }
    }
    int[] res = new int[result.size()];
    for (int i = 0; i < result.size(); i++) {
        res[i] = result.get(i);
    }
    return res;
    }
}

总结:本题的难点是终止条件的判断,以及最大的众数的切换的条件,迭代的思路与上一题中大致相同,只需要注意条件的改变。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值