Skip to content

Commit f449a1e

Browse files
committed
fix: solution 함수 추가
1 parent 3cfbbfe commit f449a1e

File tree

1 file changed

+18
-14
lines changed
  • construct-binary-tree-from-preorder-and-inorder-traversal

1 file changed

+18
-14
lines changed
Lines changed: 18 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
/**
2+
* [Idea]
23
* preorder는 val -> left -> right
34
* inorder는 left -> val -> right
45
* 따라서 preorder의 val을 기준으로 inorder 배열을 왼, 오로 나누면 val의 왼쪽 트리, 오른쪽 트리 구조가 된다.
@@ -9,20 +10,23 @@
910
* node.right = leftAndRight[1]
1011
*
1112
* 구현이 안되어 코드 참고 ...
13+
* 직접 배열을 나누지 않고, val의 인덱스를 찾아 그 값을 기준으로 slice된 배열을 재귀적으로 buildTree에 넣는다.
1214
*
1315
*/
1416

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;
17+
var buildTree = function (preorder, inorder) {
18+
if (preorder.length === 0 || inorder.length === 0) {
19+
return null;
20+
}
21+
const root = new TreeNode(preorder[0]);
22+
const rootIndex = inorder.indexOf(root.val);
23+
root.left = buildTree(
24+
preorder.slice(1, rootIndex + 1),
25+
inorder.slice(0, rootIndex)
26+
);
27+
root.right = buildTree(
28+
preorder.slice(rootIndex + 1, preorder.length),
29+
inorder.slice(rootIndex + 1, inorder.length)
30+
);
31+
return root;
32+
};

0 commit comments

Comments
 (0)