-
-
Notifications
You must be signed in to change notification settings - Fork 300
/
450.java
136 lines (118 loc) · 3.4 KB
/
450.java
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
__________________________________________________________________________________________________
Runtime: 0 ms
Memory Usage: 38.4 MB
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
TreeNode prevNode = null, cur = root;
boolean leftChild = false, nodeFound = false;
while(cur != null){
if(cur.val == key){
nodeFound = true;
break;
}
prevNode = cur;
if(cur.val > key){
leftChild = true;
cur = cur.left;
}
else{
leftChild = false;
cur = cur.right;
}
}
if(!nodeFound){
return root;
}
if(prevNode == null){
return deleteNode(cur);
}
if(leftChild){
prevNode.left = deleteNode(cur);
}
else{
prevNode.right = deleteNode(cur);
}
return root;
}
private TreeNode deleteNode(TreeNode node){
if(node.left == null && node.right == null){
return null;
}
if(node.left != null && node.right != null){
TreeNode minRightSubtreeNode = findAndDeleteMinRightSubtree(node);
node.val = minRightSubtreeNode.val;
}
else if(node.left != null){
node = node.left;
}
else{
node = node.right;
}
return node;
}
private TreeNode findAndDeleteMinRightSubtree(TreeNode node){
TreeNode prevNode = node;
node = node.right;
boolean rightChild = node.left == null;
while(node.left != null){
prevNode = node;
node = node.left;
}
if(rightChild){
prevNode.right = node.right;
}
else{
prevNode.left = node.right;
}
node.right = null;
return node;
}
}
__________________________________________________________________________________________________
sample 38432 kb submission
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
if (root == null) {
return null;
} else if (key < root.val) {
root.left = deleteNode(root.left, key);
} else if (key > root.val) {
root.right = deleteNode(root.right, key);
} else {
if (root.right == null) {
return root.left;
}
if (root.left == null) {
return root.right;
}
root.val = findMin(root.right);
root.right = deleteNode(root.right, root.val);
}
return root;
}
private int findMin(TreeNode root) {
while (root.left != null) {
root = root.left;
}
return root.val;
}
}
__________________________________________________________________________________________________