代码随想录算法训练营第二十一天 | 530.二叉搜索树的最小绝对差 & 501. 二叉搜索树中的众数 & 236. 二叉树的最近公共祖先

1. 二叉搜索树的最小绝对差

530. 二叉搜索树的最小绝对差 - 力扣(LeetCode)

pre指针指向前一个节点

注意一开始pre是null(可以理解为最左节点的左孩子null)

class Solution {
    TreeNode pre = null;
    int res = Integer.MAX_VALUE;
    public int getMinimumDifference(TreeNode root) {
        deal(root);
        return res;
    }

    public void deal(TreeNode root){
        if(root == null) return ;

        deal(root.left);
        if(pre != null) 
            res = Math.min(res, root.val - pre.val);
        pre = root;
        deal(root.right);
    }
}

2. 二叉搜索树中的众数

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

当pre的值等于cur的值,count++, 否则重置为1

当count == max时,直接向res里添加当前值

如果,count > max,说明当前值的数量是所有遍历过的元素中最多的

        此时,max=count,并清空res,添加当前值

class Solution {
    int max;
    int count;
    ArrayList<Integer> res;
    TreeNode pre;

    public int[] findMode(TreeNode root) {
        res = new ArrayList<>();
        deal(root);
        int[] temp = new int[res.size()];
        for (int i = 0; i < res.size(); i++) {
            temp[i] = res.get(i);
        }
        return temp;
    }

    public void deal(TreeNode root) {
        if(root == null) return;

        deal(root.left);

        if(pre == null || root.val != pre.val)  
            count = 1;
        else 
            count++;
        if(count > max){
            max = count;
            res.clear();
            res.add(root.val);
        }else if(count == max){
            res.add(root.val);
        }

        pre = root;
        deal(root.right);
    }
}

3. 二叉树的最近公共祖先

视频讲解

236. 二叉树的最近公共祖先 - 力扣(LeetCode)

当前节点等于pq其中一个,即可返回当前节点

遍历左右子树,将其结果返回给上一层的中间节点

中间节点,判断左右子树的返回情况

左右子树中pq都找到了,则返回当前节点

找到其中一个,返回找到的节点

都没找到返回null

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null || root == p || root == q) return root;

        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);

        if(left != null && right != null) return root;
        if(left != null) return left;
        if(right != null) return right;
        return null;
    }
}

情况1:pq不在同一个子树,按照上面的步骤很清晰

情况2:pq在同一个子树(p或者q作为子树的根,另一个在它的子树中),

        那么在向下的过程中,可以直接返回这个root,不用向下再遍历了,即第一行判断

如果是情况2,那么另一个元素一定在这个root下,这个root就是最近公共祖先

不是情况2,则恢复到情况1的步骤,继续比较左右子树

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值