Skip to content

Commit 7d37a06

Browse files
authored
Update 105-construct-binary-tree-from-preorder-and-inorder-traversal.js
1 parent 0243cdd commit 7d37a06

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

105-construct-binary-tree-from-preorder-and-inorder-traversal.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +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+
const buildTree = function(preorder, inorder) {
14+
if(preorder.length === 0 && inorder.length === 0) return null
15+
const val = preorder[0]
16+
const node = new TreeNode(val)
17+
const inIdx = inorder.indexOf(val)
18+
const leftIn = inorder.slice(0, inIdx)
19+
const rightIn = inorder.slice(inIdx + 1)
20+
21+
const leftPre = preorder.slice(1, leftIn.length + 1)
22+
const rightPre = preorder.slice(leftIn.length + 1)
23+
24+
// console.log(leftIn, rightIn, leftPre, rightPre)
25+
node.left = buildTree(leftPre, leftIn)
26+
node.right = buildTree(rightPre, rightIn)
27+
return node
28+
};
29+
30+
31+
// another
32+
33+
134
/**
235
* Definition for a binary tree node.
336
* function TreeNode(val) {

0 commit comments

Comments
 (0)