My Fortieth Page - 二叉搜索树中的众树 - By Nicolas

今天的这篇page是针对leetcode501.二叉搜索树中的众数所写的。小尼先简单的说明一下这道题的意思,给出一个含重复值的二叉搜索树(BST)的根节点root,找出并返回BST中的所有众数。这里面的思路其实和上一篇文章运用的思路是一样的,都是利用一个比较的思路求解。

小尼首先给出递归的解法,首先就是我们定义一个count数值用于记录重复项的个数,然后我们不断与我们之前取到的maxCount的值进行比较,当大于时我们的maxCount就去用count取代,小尼接下来给出代码:

class Solution {
    ArrayList<Integer> reList;
    int maxCount;
    int count;
    TreeNode pre;

    public int[] findMode(TreeNode root) {
        reList = new ArrayList<>();
        maxCount = 0;
        count = 0;
        pre = null;
        findMode1(root);
        int[] res = new int[reList.size()];
        for(int i = 0;i<reList.size();i++){
            res[i] = reList.get(i);
        }
        return res;
    }

    public void findMode1(TreeNode root){
        if(root == null){
            return;
        }
        findMode1(root.left);

        int rootValue = root.val;
        if(pre == null || rootValue != pre.val){
            count = 1;
        }else{
            count++;
        }
        if(count > maxCount) {
            reList.clear();
            reList.add(rootValue);
            maxCount = count;
        }else if(count == maxCount){
            reList.add(rootValue);
        }
        pre = root;
        findMode1(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;
            }
        }
        return result.stream().mapToInt(Integer::intValue).toArray();
    }
}

其实迭代法的解法根递归的区别不是很大,迭代法这边只是使用while循环代替了上面的递归的作用,其他语句的使用差别不大

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值