Day 21 | 235. 二叉搜索树的最近公共祖先,701.二叉搜索树中的插入操作,450.删除二叉搜索树中的节点

235. 二叉搜索树的最近公共祖先

如果不是二叉搜索树的话,使用后序遍历回溯。

二叉搜索树的话,如果 p 和 q 的值的大小刚好在 root的两边, (p < root < q or q < root < q),则 root 为p,q的最近公共祖先。

代码:

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        // if (root == null) return null;
        if (root.val > p.val && root.val > q.val) return lowestCommonAncestor(root.left, p, q);
        if (root.val < p.val && root.val < q.val) return lowestCommonAncestor(root.right, p, q);
        return root;
    }
}

701.二叉搜索树中的插入操作

在这里插入图片描述

其实不需要改变树结构,不需要考虑插入后的树是否为二叉搜索树。

利用二叉搜索树树的特点,遇到null 则创建节点,并返回。

450.删除二叉搜索树中的节点

难点在于调整删除节点的左右子树。分清楚情况分别处理即可。

  1. 左右子树均为空:直接返回空
  2. 左子树不为空,右子树为空:直接返回左孩子
  3. 左子树为空,右子树不为空:直接返回右孩子
  4. 左右子树都不为空:需要将左子树移动到右子树的最左边节点的左孩子。
if (root.left == null && root.right == null) return null;
else if (root.left != null && root.right == null) return root.left;
else if (root.left == null && root.right != null) return root.right;
else {
    TreeNode temp = root.right;
    while (temp.left != null) {
        temp = temp.left;
    }
    temp.left = root.left;
    return root.right;
}

简洁代码:

if (root.left == null) return root.right;
if (root.right == null) return root.left;

TreeNode temp = root.right;
while (temp.left != null) {
    temp = temp.left;
}
temp.left = root.left;
return root.right;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值