450 Delete Node in a BST

来源:互联网 发布:儿童羽绒服推荐知乎 编辑:程序博客网 时间:2024/06/05 03:49

这就是一道很基础的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
原创粉丝点击