450 Delete Node in a BST

这就是一道很基础的BST搜索树的题,自己应该写过,在MyEclipse里应该有保存,更完整的版本应该是有所有基本方法,insert,find,然后就是这个delete

递归调用的思路:

1,非常重要的一点就是:返回的是一个树的root!!这个root就是一个node,可以被其他的node通过left,right 连接上的

2,通过值的大小进行二分法的缩小范围

3,如果相等,也就是说找到了目标node,分情况讨论:1)无left child,返回right child,2)无right child 同理,3)left 和 right child都有的话,那就要寻求一个 做最小 movement 仍然保证BST不变的 方案,那就找左子树的最大值或者右子树的最小值,把这个值赋值给当前root,然后相应的 递归调用 delete函数,然后把 替换node的值作为新的key

代码如下,性能75%

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode deleteNode(TreeNode root, int key) {
        if(root==null) return root;
        if(key<root.val){
            root.left=deleteNode(root.left, key); //!!! recursively calling
        }else if(key>root.val){
            root.right=deleteNode(root.right, key); //!!! recursively calling
        }else{
            if(root.left==null) return root.right;
            if(root.right==null) return root.left;
            
            TreeNode min= findMin(root.right);
            root.val=min.val;
            root.right=deleteNode(root.right, min.val); //!!! recursively calling !!! also, it is not key now, is the min.val
        }
        return root;
    }
    
    private TreeNode findMin(TreeNode node){
        TreeNode curr=node;
        while(curr.left!=null){
            curr=curr.left;
        }
        return curr; 
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值