File tree Expand file tree Collapse file tree 1 file changed +28
-0
lines changed
construct-binary-tree-from-preorder-and-inorder-traversal Expand file tree Collapse file tree 1 file changed +28
-0
lines changed Original file line number Diff line number Diff line change
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 ;
You can’t perform that action at this time.
0 commit comments