-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBSTConstruction.java
More file actions
107 lines (100 loc) · 2.3 KB
/
BSTConstruction.java
File metadata and controls
107 lines (100 loc) · 2.3 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
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
import java.util.*;
class Program {
static class BST {
public int value;
public BST left;
public BST right;
public BST(int value) {
this.value = value;
}
// Average: O(log(n)) time | O(log(n)) space
// Worst O(n) time | O(n) space
public BST insert(int value) {
// Write your code here.
// Do not edit the return statement of this method.
if (value < this.value) {
if (left == null) {
BST newBST = new BST(value);
left = newBST;
} else {
left.insert(value);
}
} else {
if (right == null) {
BST newBST = new BST(value);
right = newBST;
} else {
right.insert(value);
}
}
return this;
}
// Average: O(log(n)) time | O(log(n)) space
// Worst O(n) time | O(n) space
public boolean contains(int value) {
// Write your code here.
if (value < this.value) {
if (left == null) {
return false;
} else {
return left.contains(value);
}
} else if (value > this.value) {
if (right == null) {
return false;
} else {
return right.contains(value);
}
} else {
return true;
}
}
// Average: O(log(n)) time | O(log(n)) space
// Worst O(n) time | O(n) space
public BST remove(int value) {
// Write your code here.
// Do not edit the return statement of this method.
remove(value, null);
return this;
}
private void remove(int value, BST parent) {
if (value < this.value) {
if (left != null) {
left.remove(value, this);
}
} else if (value > this.value) {
if (right != null) {
right.remove(value, this);
}
} else {
if (left != null && right != null) {
this.value = right.getMinValue();
right.remove(this.value, this);
} else if (parent == null) {
if (left != null) {
this.value = left.value;
right = left.right;
left = left.left;
} else if (right != null) {
this.value = right.value;
left = right.left;
right = right.right;
} else {
// do nothing
}
} else if (parent.left == this) {
parent.left = left != null ? left : right;
} else if (parent.right == this) {
parent.right = left != null ? left : right;
}
}
}
private int getMinValue() {
if (left == null) {
return this.value;
} else {
return left.getMinValue();
}
}
}
}