forked from striver79/FreeKaTreeSeries
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdeleteNodeBstJava
47 lines (47 loc) · 1.4 KB
/
deleteNodeBstJava
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
class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
if (root == null) {
return null;
}
if (root.val == key) {
return helper(root);
}
TreeNode dummy = root;
while (root != null) {
if (root.val > key) {
if (root.left != null && root.left.val == key) {
root.left = helper(root.left);
break;
} else {
root = root.left;
}
} else {
if (root.right != null && root.right.val == key) {
root.right = helper(root.right);
break;
} else {
root = root.right;
}
}
}
return dummy;
}
public TreeNode helper(TreeNode root) {
if (root.left == null) {
return root.right;
} else if (root.right == null){
return root.left;
} else {
TreeNode rightChild = root.right;
TreeNode lastRight = findLastRight(root.left);
lastRight.right = rightChild;
return root.left;
}
}
public TreeNode findLastRight(TreeNode root) {
if (root.right == null) {
return root;
}
return findLastRight(root.right);
}
}