File tree Expand file tree Collapse file tree 1 file changed +12
-17
lines changed Expand file tree Collapse file tree 1 file changed +12
-17
lines changed Original file line number Diff line number Diff line change 1
1
/**
2
- * https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
3
- *
4
- * 105. 从前序与中序遍历序列构造二叉树
5
- *
6
- * Medium
7
- *
8
- * 根 左 右
9
- *
10
- * 左 根 右
2
+ * 时间复杂度:O(n)
3
+ * 空间复杂度:O(n)
11
4
*/
12
5
const buildTree = ( preorder , inorder ) => {
13
6
if ( preorder . length === 0 ) {
14
- return null
7
+ return null ;
15
8
}
16
- const rootValue = preorder . shift ( )
17
- const root = new TreeNode ( rootValue )
18
- // 左右子树的分割点
19
- const index = inorder . indexOf ( rootValue )
20
9
21
- root . left = buildTree ( preorder . slice ( 0 , index ) , inorder . slice ( 0 , index ) )
22
- root . right = buildTree ( preorder . slice ( index ) , inorder . slice ( index + 1 ) )
10
+ const rootValue = preorder . shift ( ) ;
23
11
24
- return root
12
+ const root = new TreeNode ( rootValue ) ;
13
+
14
+ const index = inorder . indexOf ( rootValue ) ;
15
+
16
+ root . left = buildTree ( preorder . slice ( 0 , index ) , inorder . slice ( 0 , index ) ) ;
17
+ root . right = buildTree ( preorder . slice ( index ) , inorder . slice ( index + 1 ) ) ;
18
+
19
+ return root ;
25
20
}
You can’t perform that action at this time.
0 commit comments