8000 feat(105): 第一种解法 · descire/LeetCode@f303aee · GitHub
[go: up one dir, main page]

Skip to content

Commit f303aee

Browse files
committed
feat(105): 第一种解法
1 parent b4f7592 commit f303aee

File tree

3 files changed

+25
-54
lines changed

3 files changed

+25
-54
lines changed

Binary-Tree/1008/solution2.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
2+
const buildTree = (preorder, inorder) => {
3+
if (preorder.length === 0) {
4+
return null;
5+
}
6+
7+
const rootValue = preorder.shift();
8+
9+
const root = new TreeNode(rootValue);
10+
11+
const index = inorder.indexOf(rootValue);
12+
13+
root.left = buildTree(preorder.slice(0, index), inorder.slice(0, index));
14+
root.right = buildTree(preorder.slice(index), inorder.slice(index + 1));
15+
16+
return root;
17+
}

Binary-Tree/105/readme.md

Lines changed: 0 additions & 48 deletions
This file was deleted.

Binary-Tree/105/solution1.js

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,22 @@
11
/**
2-
* 时间复杂度:O(n)
2+
* 时间复杂度:O(n^2)
33
* 空间复杂度:O(n)
44
*/
55
const buildTree = (preorder, inorder) => {
6+
// 递归中止条件
67
if (preorder.length === 0) {
78
return null;
89
}
910

10-
const rootValue = preorder.shift();
11+
const rootElement = preorder[0];
1112

12-
const root = new TreeNode(rootValue);
13+
const root = new TreeNode(rootElement);
1314

14-
const index = inorder.indexOf(rootValue);
15+
const rootElementIndex = inorder.indexOf(rootElement);
1516

16-
root.left = buildTree(preorder.slice(0, index), inorder.slice(0, index));
17-
root.right = buildTree(preorder.slice(index), inorder.slice(index + 1));
17+
root.left = buildTree(preorder.slice(1, rootElementIndex + 1), inorder.slice(0, rootElementIndex));
18+
19+
root.right = buildTree(preorder.slice(rootElementIndex + 1), inorder.slice(rootElementIndex + 1));
1820

1921
return root;
2022
}

0 commit comments

Comments
 (0)
0