-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDelete In Binary Search Tree.java
62 lines (57 loc) · 1.48 KB
/
Delete In Binary Search Tree.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
/*
Delete the target key K in the given binary search tree if the binary search tree contains K.
Return the root of the binary search tree.
Find your own way to delete the node from the binary search tree,
after deletion the binary search tree's property should be maintained.
Assumptions
There are no duplicate keys in the binary search tree
time = O(height)
space = O(height)
*/
/**
* public class TreeNode {
* public int key;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int key) {
* this.key = key;
* }
* }
*/
public class Solution {
public TreeNode delete(TreeNode root, int key) {
// Write your solution here
if (root == null) {
return root;
}
if (key == root.key) {
if (root.left == null) {
return root.right;
} else if (root.right == null) {
return root.left;
} else if (root.right.left == null) {
root.right.left = root.left;
return root.right;
} else {
TreeNode newRoot = deleteSmallest(root.right);
newRoot.left = root.left;
newRoot.right = root.right;
return newRoot;
}
}
if (root.key < key) {
root.right = delete(root.right, key);
} else {
root.left = delete(root.left, key);
}
return root;
}
private TreeNode deleteSmallest(TreeNode root) {
while (root.left.left != null) {
root = root.left;
}
TreeNode smallest = root.left;
root.left = root.left.right;
return smallest;
}
}