generated from filipe1309/shubcogen-template
-
Notifications
You must be signed in to change notification settings - Fork 6
/
solution-2.ts
34 lines (29 loc) · 1.11 KB
/
solution-2.ts
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
import { BST } from "./solution"
class TreeInfo {
rootIdx: number;
constructor(rootIdx: number) {
this.rootIdx = rootIdx;
}
}
// Lower Upper Bounds approach
// Complexity (worst-case): time O(n) | space O(n)
function reconstructBst(preOrderTraversalValues: number[]): BST | null {
let treeInfo = new TreeInfo(0);
return reconstructBstFromRange(-Infinity, Infinity, preOrderTraversalValues, treeInfo);
}
function reconstructBstFromRange(
lowerBound: number,
upperBound: number,
preOrderTraversalValues: number[],
currSubtreeInfo: TreeInfo
) : BST | null
{
if (currSubtreeInfo.rootIdx === preOrderTraversalValues.length) return null;
let rootValue = preOrderTraversalValues[currSubtreeInfo.rootIdx];
if (rootValue < lowerBound || rootValue >= upperBound) return null
currSubtreeInfo.rootIdx++;
let leftSubtree = reconstructBstFromRange(lowerBound, rootValue, preOrderTraversalValues, currSubtreeInfo);
let rightSubtree = reconstructBstFromRange(rootValue, upperBound, preOrderTraversalValues, currSubtreeInfo);
return new BST(rootValue, leftSubtree, rightSubtree);
}
export default reconstructBst;