6.26 删除二叉搜索树中的结点——【LeetCode】

在这里插入图片描述
在这里插入图片描述


class Solution {
    //法一
    public TreeNode deleteNode(TreeNode root, int key) {
        root = delete(root, key);
        return root;
    }

    private TreeNode delete(TreeNode root, int key) {
        if(root == null){
            return null;
        }
        if(root.val > key){// 向左查找
            root.left = delete(root.left, key);
        }else if(root.val < key){// 向右查找
            root.right = delete(root.right, key);
        }else {// 找到要删除的结点了 即root结点
            //分为三种情况,左结点为空、右结点为空、左右都不为空
            if(root.left == null){
                return root.right;
            }
            if(root.right == null){
                return root.left;
            }
            // 如果左右结点都不为空
            TreeNode tmp = root.right;//tmp用来遍历查找到大于当前root的最小值
            while (tmp.left != null){
                tmp = tmp.left;// 即一直迭代查找到大于当前root的最小值,即是右子树的最左边的值
            }
            // 这里理解为:例题图中先让4替换3 然后再删除4结点
            root.val = tmp.val;// 然后把找到的tmp值赋值给root.val, 并删除掉tmp结点
            root.right = delete(root.right, tmp.val);
        }
        return root;
    }

    //法二
    public TreeNode deleteNode1(TreeNode root, int key) {
        if(root == null){
            return root;
        }

        if(root.val == key){
            if(root.left == null){
                return root.right;
            }else if(root.right == null){
                return root.left;
            }else{
                TreeNode cur = root.right;
                while (cur.left != null){
                    cur = cur.left;
                }
                // 这里可以理解为:图中的2先挂在4左边 然后4替换3结点
                cur.left = root.left;// root.left结点的值必定是小于cur.left的 所以这里没毛病
                root = root.right;
                return root;
            }
        }

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

}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

DZSpace

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值