Skip to content

Commit 35e5aaa

Browse files
committed
feat: 105. Construct Binary Tree from Preorder and Inorder Traversal
1 parent ddc84aa commit 35e5aaa

File tree

1 file changed

+27
-0
lines changed
  • construct-binary-tree-from-preorder-and-inorder-traversal

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// Time complexity: O(n^2)
2+
// Space complexity: O(n)
3+
4+
/**
5+
* Definition for a binary tree node.
6+
* function TreeNode(val, left, right) {
7+
* this.val = (val===undefined ? 0 : val)
8+
* this.left = (left===undefined ? null : left)
9+
* this.right = (right===undefined ? null : right)
10+
* }
11+
*/
12+
/**
13+
* @param {number[]} preorder
14+
* @param {number[]} inorder
15+
* @return {TreeNode}
16+
*/
17+
var buildTree = function (preorder, inorder) {
18+
if (!preorder.length || !inorder.length) return null;
19+
20+
const root = new TreeNode(preorder[0]);
21+
const mid = inorder.indexOf(root.val);
22+
23+
root.left = buildTree(preorder.slice(1, mid + 1), inorder.slice(0, mid));
24+
root.right = buildTree(preorder.slice(mid + 1), inorder.slice(mid + 1));
25+
26+
return root;
27+
};

0 commit comments

Comments
 (0)