-
Notifications
You must be signed in to change notification settings - Fork 3
/
removeNodeBST.cpp
73 lines (63 loc) · 2.11 KB
/
removeNodeBST.cpp
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
public class Solution {
/**
* @param root: The root of the binary search tree.
* @param value: Remove the node with given value.
* @return: The root of the binary search tree after removal.
*/
public TreeNode removeNode(TreeNode root, int value) {
TreeNode dummy = new TreeNode(0);
dummy.left = root;
TreeNode parent = findNode(dummy, root, value);
TreeNode node;
if (parent.left != null && parent.left.val == value) {
node = parent.left;
} else if (parent.right != null && parent.right.val == value) {
node = parent.right;
} else {
return dummy.left;
}
deleteNode(parent, node);
return dummy.left;
}
private TreeNode findNode(TreeNode parent, TreeNode node, int value) {
if (node == null) {
return parent;
}
if (node.val == value) {
return parent;
}
if (value < node.val) {
return findNode(node, node.left, value);
} else {
return findNode(node, node.right, value);
}
}
private void deleteNode(TreeNode parent, TreeNode node) {
if (node.right == null) {
if (parent.left == node) {
parent.left = node.left;
} else {
parent.right = node.left;
}
} else {
TreeNode temp = node.right;
TreeNode father = node;
while (temp.left != null) {
father = temp;
temp = temp.left;
}
if (father.left == temp) {
father.left = temp.right;
} else {
father.right = temp.right;
}
if (parent.left == node) {
parent.left = temp;
} else {
parent.right = temp;
}
temp.left = node.left;
temp.right = node.right;
}
}
}