Skip to content

Commit c2ef4b3

Browse files
committed
Construct Binary Tree from Preorder and Inorder Traversal / 중급
1 parent 98fa450 commit c2ef4b3

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val, left, right) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.left = (left===undefined ? null : left)
6+
* this.right = (right===undefined ? null : right)
7+
* }
8+
*/
9+
/**
10+
* @param {number[]} preorder
11+
* @param {number[]} inorder
12+
* @return {TreeNode}
13+
*/
14+
var buildTree = function (preorder, inorder) {
15+
const inorderMap = new Map();
16+
inorder.forEach((val, idx) => inorderMap.set(val, idx));
17+
18+
function build(preStart, preEnd, inStart, inEnd) {
19+
if (preStart > preEnd || inStart > inEnd) return null;
20+
21+
const rootVal = preorder[preStart];
22+
const root = new TreeNode(rootVal);
23+
const inRootIndex = inorderMap.get(rootVal);
24+
const leftSize = inRootIndex - inStart;
25+
26+
root.left = build(
27+
preStart + 1,
28+
preStart + leftSize,
29+
inStart,
30+
inRootIndex - 1
31+
);
32+
root.right = build(preStart + leftSize + 1, preEnd, inRootIndex + 1, inEnd);
33+
34+
return root;
35+
}
36+
37+
return build(0, preorder.length - 1, 0, inorder.length - 1);
38+
};

0 commit comments

Comments
 (0)