|
1 | 1 | /**
|
| 2 | + * [Idea] |
2 | 3 | * preorder는 val -> left -> right
|
3 | 4 | * inorder는 left -> val -> right
|
4 | 5 | * 따라서 preorder의 val을 기준으로 inorder 배열을 왼, 오로 나누면 val의 왼쪽 트리, 오른쪽 트리 구조가 된다.
|
|
9 | 10 | * node.right = leftAndRight[1]
|
10 | 11 | *
|
11 | 12 | * 구현이 안되어 코드 참고 ...
|
| 13 | + * 직접 배열을 나누지 않고, val의 인덱스를 찾아 그 값을 기준으로 slice된 배열을 재귀적으로 buildTree에 넣는다. |
12 | 14 | *
|
13 | 15 | */
|
14 | 16 |
|
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