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:

  1. Search for a node to remove.
  2. If the node is found, delete the node.

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

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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

思路

首先我们需要搜索这棵树,找到待删除节点的父亲节点。利用二叉搜索树的条件,可以对树进行二分搜索,搜索的复杂度就是树高了。

我们需要对节点进行删除操作,判断条件实际上就是三种情况:待删除的节点没有左右子树,有左/右子树,有左右子树。特别注意的是,有左右子树的情况,需要找到比待删除节点刚好大一点的数,也就是待删除节点右节点的最左端的节点。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/**
* 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 searchNode(TreeNode node, int key){
if(node.left == null && node.right == null) return null;
else{
int leftval = -1;
int rightval = -1;
if(node.left != null) leftval = node.left.val;
if(node.right != null) rightval = node.right.val;
if(key == leftval || key == rightval) return node;
else{
if(key < node.val) return searchNode(node.left, key);
else return searchNode(node.right, key);
}
}
}
public TreeNode deleteNode(TreeNode root, int key) {
if(root == null) return root;
TreeNode node = root;
TreeNode parent = null;
Boolean left = true;
if(root.val != key){
parent = searchNode(root, key);
if(parent == null) return root;
if(parent.left != null) if(parent.left.val == key) node = parent.left;
if(parent.right != null) {
if(parent.right.val == key){
node = parent.right;
left = false;
}
}
}
if(node.left == null && node.right == null){
if(parent == null) return null;
if(left) parent.left = null;
else parent.right = null;
}
else if(node.right != null && node.left == null){
if(parent == null) return node.right;
else{
if(left) parent.left = node.right;
else parent.right = node.right;
}
}
else if(node.right == null && node.left != null){
if(parent == null) return node.left;
else{
if(left) parent.left = node.left;
else parent.right = node.left;
}
}
else{
if(node.right != null){
TreeNode leftmost = node.right;
TreeNode leftmost_parent = node;
while(leftmost.left != null){
leftmost_parent = leftmost;
leftmost = leftmost.left;
}
node.val = leftmost.val;
if(leftmost_parent == node) node.right = node.right.right;
else leftmost_parent.left = leftmost.right;
}
else{
node.right = null;
}
}
return root;
}
}