代码随想录day22|235. 二叉搜索树的最近公共祖先、 701.二叉搜索树中的插入操作、450.删除二叉搜索树中的节点

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

注意:√

  1. 昨天在解决二叉树LCA问题的时候看到了Labuladong书中的内容,让这题变得简单,核心是要处理一个find(root, val1, val2)的问题
  2. 注意一开始会有担心觉得为什么root节点在val1<=root<=val2就是最后的结果,因为root节点是分界点,分界的root.left一定是比root小的,必然不会存在val2的节点。
  3. 即root节点就是分支的点,一定要注意这个问题
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        int val1 = Math.min(p.val, q.val);
        int val2 = Math.max(p.val, q.val);
        return find(root, val1, val2);
    }

    private TreeNode find(TreeNode root, int val1, int val2) {
        if (root == null){
            return null;
        }

        if (root.val> val2){
            return find(root.left, val1, val2);
        }
        if (root.val< val1){
            return find(root.right, val1, val2);
        }
        return root;

    }

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

注意:×

  1. 第一遍写错了,直接将字数返回了,但是实际上正是用root.left = insertIntoBST(root.left, val);的方式将子树接在上面
    public TreeNode insertIntoBST(TreeNode root, int val) {
        if (root == null) {
            return new TreeNode(val);
        }

        if (root.val > val) {
            root.left = insertIntoBST(root.left, val);
        }

        if (root.val < val) {
            root.right = insertIntoBST(root.right, val);
        }
        
        return root;
    }

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

    //     if (root.val > val) {
    //         return insertIntoBST(root.left, val);
    //     }

    //     if (root.val < val) {
    //         return insertIntoBST(root.right, val);
    //     }
        
    //     return root;
    // }

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

注意:√

  1. 详细看完了Labuladong以后复现的,注意回头看
    public TreeNode deleteNode(TreeNode root, int key) {
        if (root == null){
            return null;
        }
        
        if (root.val == key){
            if (root.left == null){
                return root.right;
            }
            if (root.right == null){
                return root.left;
            }
            TreeNode minNode = getMin(root.right);
            root.val = minNode.val;
            root.right = deleteNode(root.right, minNode.val);
        } else if (root.val > key) {
            root.left = deleteNode(root.left, key);
        } else if (root.val < key) {
            root.right = deleteNode(root.right, key);
        }
        return root;
    }

    private TreeNode getMin(TreeNode right) {
        while (right.left!= null){
            right = right.left;
        }
        return right;
    }
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值