Skip to content

Commit 64863b7

Browse files
authored
Create 1008-construct-binary-search-tree-from-preorder-traversal.js
1 parent f671ebe commit 64863b7

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val) {
4+
* this.val = val;
5+
* this.left = this.right = null;
6+
* }
7+
*/
8+
/**
9+
* @param {number[]} preorder
10+
* @return {TreeNode}
11+
*/
12+
const bstFromPreorder = function(preorder) {
13+
let preIndex = { index: 0 };
14+
return constructTreeUtil(
15+
preorder,
16+
preIndex,
17+
preorder[0],
18+
Number.MIN_SAFE_INTEGER,
19+
Number.MAX_SAFE_INTEGER,
20+
preorder.length
21+
);
22+
function constructTreeUtil(pre, preIndex, key, min, max, size) {
23+
if (preIndex.index >= size) {
24+
return null;
25+
}
26+
let root = null;
27+
if (key > min && key < max) {
28+
root = new TreeNode(key);
29+
preIndex.index = preIndex.index + 1;
30+
if (preIndex.index < size) {
31+
root.left = constructTreeUtil(
32+
pre,
33+
preIndex,
34+
pre[preIndex.index],
35+
min,
36+
key,
37+
size
38+
);
39+
root.right = constructTreeUtil(
40+
pre,
41+
preIndex,
42+
pre[preIndex.index],
43+
key,
44+
max,
45+
size
46+
);
47+
}
48+
}
49+
return root;
50+
}
51+
};

0 commit comments

Comments
 (0)