8000 feat(107): 优化迭代解法 · descire/LeetCode@12469c6 · GitHub
[go: up one dir, main page]

Skip to content

Commit 12469c6

Browse files
committed
feat(107): 优化迭代解法
1 parent bb9d457 commit 12469c6

File tree

1 file changed

+20
-23
lines changed

1 file changed

+20
-23
lines changed

Binary-Tree/107/solution1.js

Lines changed: 20 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,29 @@
11
/**
2-
* 107. 二叉树的层次遍历 II
3-
*
4-
* https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii/
5-
*
6-
*
7-
* Easy
8-
*
9-
* 64ms 100%
10-
* 35mb 11.80%
2+
* 时间复杂度:O(n)
3+
* 空间复杂度:O(n)
114
*/
125
const levelOrderBottom = root => {
13-
const ans = []
146
if (!root) {
15-
return ans
7+
return [];
168
}
17-
const queue = [root]
9+
10+
const ans = [];
11+
let queue = [root];
12+
1813
while (queue.length) {
19-
const temp = []
20-
const max = queue.length
21-
for (let i = 0; i < max; i++) {
22-
const item = queue.pop()
23-
if (item) {
24-
temp.push(item.val)
25-
item.left && queue.unshift(item.left)
26-
item.right && queue.unshift(item.right)
14+
const len = queue.length;
15+
const item = [];
16+
const _queue = [];
17+
for (let i = 0; i < len; i++) {
18+
const currentRoot = queue[i];
19+
item.push(currentRoot.val);
20+
21+
currentRoot.left && _queue.push(currentRoot.left);
22+
currentRoot.right && _queue.push(currentRoot.right);
2723
}
28-
}
29-
ans.unshift(temp)
24+
queue = _queue;
25+
ans.push(item);
3026
}
31-
return ans
27+
ans.reverse();
28+
return ans;
3229
}

0 commit comments

Comments
 (0)
0