-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution.js
46 lines (37 loc) · 1.05 KB
/
solution.js
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class TreeNode {
constructor(val, left, right) {
this.val = (val === undefined ? 0 : val);
this.left = (left === undefined ? null : left);
this.right = (right === undefined ? null : right);
}
}
/**
* @param {number[]} preorder
* @param {number[]} inorder
* @return {TreeNode}
*/
var buildTree = function (preorder, inorder) {
let tree = new TreeNode()
const buildNode = (node, order) => {
if (0 === order.length) return;
let curr = preorder.shift();
if (!order.includes(curr)) return;
let
tmpInorder1 = [...order],
tmpInorder2 = [...order],
inIdx = order.indexOf(curr),
leftInorder = tmpInorder1.splice(0, inIdx),
rightInorder = tmpInorder2.splice(inIdx + 1, tmpInorder2.length - 1);
node.val = curr;
if (leftInorder.length > 0) {
node.left = new TreeNode();
buildNode(node.left, leftInorder);
}
if (rightInorder.length > 0) {
node.right = new TreeNode();
buildNode(node.right, rightInorder);
}
}
buildNode(tree, [...inorder]);
return tree;
};