Skip to content

Commit 3cfbbfe

Browse files
committed
Construct Binary Tree from Preorder and Inorder Traversal Solution
1 parent 6f9a973 commit 3cfbbfe

File tree

1 file changed

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

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* preorder는 val -> left -> right
3+
* inorder는 left -> val -> right
4+
* 따라서 preorder의 val을 기준으로 inorder 배열을 왼, 오로 나누면 val의 왼쪽 트리, 오른쪽 트리 구조가 된다.
5+
*
6+
* node.val = preorder[i]
7+
* const leftAndRight = inorder.split(preorder[0])
8+
* node.left = leftAndRight[0]
9+
* node.right = leftAndRight[1]
10+
*
11+
* 구현이 안되어 코드 참고 ...
12+
*
13+
*/
14+
15+
if (preorder.length === 0 || inorder.length === 0) {
16+
return null;
17+
}
18+
const root = new TreeNode(preorder[0]);
19+
const rootIndex = inorder.indexOf(root.val);
20+
root.left = buildTree(
21+
preorder.slice(1, rootIndex + 1),
22+
inorder.slice(0, rootIndex)
23+
);
24+
root.right = buildTree(
25+
preorder.slice(rootIndex + 1, preorder.length),
26+
inorder.slice(rootIndex + 1, inorder.length)
27+
);
28+
return root;

0 commit comments

Comments
 (0)