Skip to content

Commit 51c85e3

Browse files
authored
Create 105-construct-binary-tree-from-preorder-and-inorder-traversal.js
1 parent 719eec2 commit 51c85e3

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
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+
* @param {number[]} inorder
11+
* @return {TreeNode}
12+
*/
13+
let pre
14+
let ins
15+
let inmap = {}
16+
const buildTree = function(preorder, inorder) {
17+
pre = preorder
18+
ins = inorder
19+
for(let i = 0; i < inorder.length; i++) {
20+
inmap[inorder[i]] = i
21+
}
22+
let root = helper(0,0,ins.length - 1)
23+
return root
24+
};
25+
26+
function helper(preStart, inStart, inEnd) {
27+
if (preStart > pre.length -1 || inStart > inEnd) {
28+
return null
29+
}
30+
let val = pre[preStart]
31+
let root = new TreeNode(val)
32+
let inIndex = inmap[val]
33+
root.left = helper(preStart + 1, inStart, inIndex - 1)
34+
root.right = helper(preStart+inIndex-inStart+1, inIndex+1, inEnd)
35+
return root
36+
}

0 commit comments

Comments
 (0)