-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReconstructBST2.java
More file actions
38 lines (33 loc) · 1.12 KB
/
ReconstructBST2.java
File metadata and controls
38 lines (33 loc) · 1.12 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
import java.util.*;
class Program {
// This is an input class. Do not edit.
static class BST {
public int value;
public BST left = null;
public BST right = null;
public BST(int value) {
this.value = value;
}
}
private static int rootIdx;
// O(n) time | O(n) space - where n is the number of the input array
public BST reconstructBst(ArrayList<Integer> preOrderTraversalValues) {
// Write your code here.
rootIdx = 0;
return constructBst(preOrderTraversalValues, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
private static BST constructBst(ArrayList<Integer> values, int lowerBound, int upperBound) {
if (rootIdx >= values.size()) {
return null;
}
int rootValue = values.get(rootIdx);
if (rootValue < lowerBound || rootValue >= upperBound) {
return null;
}
++rootIdx;
BST root = new BST(rootValue);
root.left = constructBst(values, lowerBound, rootValue);
root.right = constructBst(values, rootValue, upperBound);
return root;
}
}