-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path1008. Construct Binary Search Tree from Preorder Traversal.js
61 lines (52 loc) · 1.7 KB
/
1008. Construct Binary Search Tree from Preorder Traversal.js
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
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {number[]} preorder
* @return {TreeNode}
*/
var bstFromPreorder = function (preorder) {
if (preorder.length === 0) return null;
let idx = 0;
return dfs(Number.MAX_SAFE_INTEGER);
function dfs(bound) {
if (preorder[idx] > bound || idx === preorder.length) return null;
let root = new TreeNode(preorder[idx]);
idx += 1
root.left = dfs(root.val);
root.right = dfs(bound);
return root;
}
};
// Solution 1: Sort preorder array, and covert sorted array to BST -> T: O(NlogN)
// Solution 2: Iterate preorder array by dfs building TreeNodes with max boundary.
// Left recursion max boundary will be node.val ,and
// right recursion max boundary can be any value (<= max integer).
// In total at most visit N nodes -> T: O(N)
// 2020/02/12 Revisited
// 1. Use destructuring passing params.
// 2. Debug: print all the params in the beginning of func dfs to show the recursion stack.
// 3. Always use Java solution because it does not support closure and params can not be hidden from helper function.
/**
* @param {number[]} preorder
* @return {TreeNode}
*/
let idx = 0;
var bstFromPreorder = function (preorder) {
if (preorder.length === 0) return null;
return dfs({ preorder, idx, bound: Number.MAX_SAFE_INTEGER });
};
function dfs({ preorder, bound }) {
console.log({ idx });
console.log({ preorder, bound });
if (preorder[idx] > bound || idx === preorder.length) return null;
let root = new TreeNode(preorder[idx]);
idx += 1;
root.left = dfs({ preorder, bound: root.val });
root.right = dfs({ preorder, bound });
return root;
}