LeeCode Practice Journal | Day20_Binary Tree07

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

题目:235. 二叉搜索树的最近公共祖先 - 力扣(LeetCode)
题解:代码随想录 (programmercarl.com)
递归的查找左右子树的条件判断更加简单了

solution:
public class Solution {
    public TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(p.val < root.val && q.val < root.val)
            return LowestCommonAncestor(root.left, p, q);
        else if(p.val > root.val && q.val > root.val)
            return LowestCommonAncestor(root.right, p, q);
        else
            return root;
    }
}
summary:

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

题目:701. 二叉搜索树中的插入操作 - 力扣(LeetCode)
题解:代码随想录 (programmercarl.com)
递归的像子树中插入节点,并返回插入节点的子树

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

        if(val < root.val) root.left = InsertIntoBST(root.left, val);
        else root.right = InsertIntoBST(root.right, val);
        return root;
    }
}
summary:

错误:

插入节点操作只创建了新节点,没有让父节点指向新节点,忽略了回溯

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

题目:450. 删除二叉搜索树中的节点 - 力扣(LeetCode)
题解:代码随想录 (programmercarl.com)
怎么样简洁的进行删除操作纠结了好一会

solution:
public class Solution {
    public TreeNode cur = null;
    public TreeNode DeleteNode(TreeNode root, int key) {
        if(root == null) return null;

        if(key < root.val) root.left = DeleteNode(root.left, key);
        else if(key > root.val) root.right = DeleteNode(root.right, key);
        else
        {
            if(root.right != null)
            {
                cur = root.right;
                while(cur.left != null) cur = cur.left;
                cur.left = root.left;
                return root.right;
            }
            else return root.left;
        }

        return root;
    }
}
summary:

key:

二叉搜索树节点的删除操作:
存在右子树时:
        删除节点的左子树成为右子树的最左节点的左子树
        删除节点的父节点指向右子树
        (顺序不可颠倒)
不存在右子树时:
        返回左子树

错误:

以为需要记录一个pre节点

删除操作的细节:
需要判断右子树是否存在

最后的return:
整个算法的逻辑用自然语言描述是若目标在节点的左子树则对左子树递归,在右子树则对右子树递归,最后返回节点,所以对左右子树操作完成后,要返回当前节点
return的本质:删除操作后的二叉树

  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值