-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
75 lines (70 loc) · 2.33 KB
/
Solution.java
File metadata and controls
75 lines (70 loc) · 2.33 KB
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
package leetCode_450;
/**
* @author dimdark
* @date 2017-09-06
* @time 10:41 PM
*/
public class Solution {
public static class TreeNode {
int val;
TreeNode left, right;
TreeNode(int x) {
val = x;
}
}
private TreeNode[] findNode(TreeNode root, int key) {
if (root == null) return null;
TreeNode node = root, fatherNode = null;
while (node != null) {
if (node.val == key) break;
else if(node.val > key) {
fatherNode = node;
node = node.left;
} else {
fatherNode = node;
node = node.right;
}
}
return new TreeNode[]{fatherNode, node};
}
public TreeNode deleteNode(TreeNode root, int key) {
TreeNode[] nodes = findNode(root, key);
if (nodes == null || nodes[1] == null) return root; // key is not in the tree
TreeNode fatherNode = nodes[0], node = nodes[1];
// delete node
if (node.left == null) {
if (fatherNode == null) {
root = node.right;
} else {
if (node == fatherNode.left) fatherNode.left = node.right;
else fatherNode.right = node.right;
}
} else if(node.right == null) {
if (fatherNode == null) {
root = node.left;
} else {
if (node == fatherNode.left) fatherNode.left = node.left;
else fatherNode.right = node.left;
}
} else {
TreeNode preNode = node, successorNode = node.right;
while (successorNode.left != null) {
preNode = successorNode;
successorNode = successorNode.left;
}
if(successorNode != node.right) {
if (successorNode == preNode.left) preNode.left = successorNode.right;
else preNode.right = successorNode.right;
successorNode.right = node.right;
}
successorNode.left = node.left;
if (fatherNode == null) {
root = successorNode;
} else {
if (node == fatherNode.left) fatherNode.left = successorNode;
else fatherNode.right = successorNode;
}
}
return root;
}
}