Tree——No.450 Delete Node in a BST

Problem:

Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST.

Note: Time complexity should be O(height of tree).

Explanation:

删除二叉搜索树中的结点。

My Thinking:

删除二叉搜索树的结点,有三种情况:

    (1)删除的是叶子结点,直接删除

    (2)删除的是只有一个孩子的结点,将唯一的孩子“结点”替换它

    (3)删除的是有两个孩子的结点,使用中序遍历后的前驱或后继结点的“值”替换它,并将原先后继结点删除

My Solution:

public TreeNode deleteBST(TreeNode root,int key){
        if(root == null){
            return null;
        }
        //通过遍历找到key的位置
        if(key < root.val){
            root.left = deleteBST(root.left, key);
        }else if(key > root.val){
            root.right = deleteBST(root.right, key);
        }else{//找到key的位置
            if(root.left == null){//没有左孩子,让右孩子替换它
                return root.right;
            }else if(root.right == null){//没有右孩子,让左孩子替换它
                return root.left;
            }
            //有两个孩子,则用后继结点的值替换它,再将其递归找到删除
            TreeNode successor = descendantNode(root);
            root.val = successor.val;
            //从右子树中找到该值并删除
            root.right = deleteBST(root.right, root.val);
        }
        return root;
    }
    //用于查找结点的后继结点,后继结点就是该结点的右子树中的最小值,只需将右子树一直向左遍历即可
    private TreeNode descendantNode(TreeNode node){
       node=node.right;
       while(node.left!=null)
           node=node.left;
       return node;
    }

Optimum Thinking:

Optimum Solution:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值