Skip to content

Commit 8c879ec

Browse files
committed
[leet] bst
1 parent 507f3e3 commit 8c879ec

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val, left, right) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.left = (left===undefined ? null : left)
6+
* this.right = (right===undefined ? null : right)
7+
* }
8+
*/
9+
/**
10+
* @param {number[]} preorder
11+
* @param {number[]} inorder
12+
* @return {TreeNode}
13+
*/
14+
var buildTree = function (preorder, inorder) {
15+
const map = new Map();
16+
17+
for (let i = 0; i < inorder.length; i++) {
18+
map.set(inorder[i], i);
19+
}
20+
21+
let preIdx = 0;
22+
23+
const build = (left, right) => {
24+
if (left > right) return null;
25+
26+
const rootVal = preorder[preIdx++];
27+
const root = new TreeNode(rootVal);
28+
29+
const mid = map.get(rootVal);
30+
31+
root.left = build(left, mid - 1);
32+
root.right = build(mid + 1, right);
33+
34+
return root;
35+
};
36+
37+
return build(0, inorder.length - 1);
38+
};

0 commit comments

Comments
 (0)