代码随想录算法训练营第二十二天 | 235. 二叉搜索树的最近公共祖先 & 701.二叉搜索树中的插入操作 & 450.删除二叉搜索树中的节点

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

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

有序的,可以根据值判断pq在哪一边

pq要么在左右子树中一边 搜索其中一边即可

要么就是 pq中的一个在根节点,另一个在其中一颗子树,返回根节点即可

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        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;
    }
}

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

701. 二叉搜索树中的插入操作 - 力扣(LeetCode)

这题要想明白,要插入的节点始终能在叶子节点下找到一个它的位置

class Solution {
    public TreeNode insertIntoBST(TreeNode root, int val) {
        if(root == null) return new TreeNode(val);

        if(val > root.val) root.right = insertIntoBST(root.right, val);
        if(val < root.val) root.left = insertIntoBST(root.left, val);

        return root;
    }
}

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

450. 删除二叉搜索树中的节点 - 力扣(LeetCode)

视频讲解

1. 找不到key

2. 找到key

2.1 叶子节点

        将null返回给上一层

2.2 左为null

        将右子树返回给上一层

2.3 右为null

        将左子树返回给上一层

2.4 左右都不为null

        将左子树挂到右子树的最左节点(该节点是第一个比左子树中最大节点大的,保证右子树的有序性)

        将右子树返回给父节点

class Solution {
    public TreeNode deleteNode(TreeNode root, int key) {
        if(root == null) return root;//1

        if(root.val == key){  //2
            if(root.left == null && root.right == null) //2.1
                return null;
            if(root.left == null) //2.2
                return root.right;
            if(root.right == null) //2.3
                return root.left;

            TreeNode cur = root.right; //2.4
            while(cur.left != null)
                cur = cur.left;
            cur.left = root.left;
            return root.right;
        }

        if(key < root.val) root.left = deleteNode(root.left, key);
        if(key > root.val) root.right = deleteNode(root.right, key);
        return root;
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值