-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path105.js
More file actions
28 lines (26 loc) · 892 Bytes
/
105.js
File metadata and controls
28 lines (26 loc) · 892 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {number[]} preorder
* @param {number[]} inorder
* @return {TreeNode}
*/
var buildTree = function(preorder, inorder) {
if (preorder.length === 0) return null;
if (preorder.length === 1) return new TreeNode(preorder[0]);
const mid = preorder[0];
const index = inorder.indexOf(mid);
const inorderLeft = inorder.slice(0, index);
const inorderRight = inorder.slice(index + 1, inorder.length);
const preorderLeft = preorder.slice(1, inorderLeft.length + 1);
const preorderRight = preorder.slice(inorderLeft.length + 1, preorder.length);
const returnValue = new TreeNode(mid);
returnValue.left = buildTree(preorderLeft, inorderLeft);
returnValue.right = buildTree(preorderRight, inorderRight);
return returnValue;
};