Delete Node in a BST
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.
Basically, the deletion can be divided into two stages:
Search for a node to remove.
If the node is found, delete the node.
Note: Time complexity should be O(height of tree).
Example:
root = [5,3,6,2,4,null,7]
key = 3
5
/ \
3 6
/ \ \
2 4 7
Given key to delete is 3. So we find the node with value 3 and delete it.
One valid answer is [5,4,6,2,null,null,7], shown in the following BST.
5
/ \
4 6
/ \
2 7
Another valid answer is [5,2,6,null,4,null,7].
5
/ \
2 6
\ \
4 7
解题思路
我们可以用递归来查找Key,在找到需要删除的节点后,我们需要分情况讨论:
1) 节点是叶子节点,直接返回null;
2) 节点有一个孩子,直接返回孩子;
3)节点有两个孩子,我们要将右子树中最小的节点值赋值给根节点,并在右子树中删除掉那个最小的节点。
2.代码
public class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
if(root==null) return root;
if(key>root.val)
root.right=deleteNode(root.right,key);
else if(key<root.val)
root.left=deleteNode(root.left,key);
else{
if(root.left!=null&&root.right!=null){
root.val=findMin(root.right).val;
root.right=deleteNode(root.right,root.val);
}
else{
if(root.left==null)
root=root.right;
else root=root.left;
}
}
return root;
}
private TreeNode findMin(TreeNode root){
TreeNode node=root;
while(node.left!=null)
node=node.left;
return node;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。