Skip to content

Commit f7c44f7

Browse files
committed
feat(105): 递归
1 parent 8716a4a commit f7c44f7

File tree

1 file changed

+12
-17
lines changed

1 file changed

+12
-17
lines changed

Binary-Tree/105/solution1.js

Lines changed: 12 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,20 @@
11
/**
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)
114
*/
125
const buildTree = (preorder, inorder) => {
136
if (preorder.length === 0) {
14-
return null
7+
return null;
158
}
16-
const rootValue = preorder.shift()
17-
const root = new TreeNode(rootValue)
18-
// 左右子树的分割点
19-
const index = inorder.indexOf(rootValue)
209

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();
2311

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;
2520
}

0 commit comments

Comments
 (0)