Skip to content

Commit caaf148

Browse files
committed
feat(102): 更新递归解法
1 parent 014e98a commit caaf148

File tree

1 file changed

+14
-18
lines changed

1 file changed

+14
-18
lines changed

Binary-Tree/102/solution2.js

Lines changed: 14 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,24 @@
11
/**
2-
* https://leetcode-cn.com/problems/binary-tree-level-order-traversal/
3-
*
4-
* 102. 二叉树的层次遍历
5-
*
6-
* Medium
7-
*
8-
* DFS
9-
*
10-
* 88ms 67.65%
11-
* 34.7mb 49.75%
2+
* 时间复杂度:O(n)
3+
* 空间复杂度:O(n)
124
*/
135
const levelOrder = root => {
14-
const ans = []
15-
dfs(root, 0, ans)
16-
return ans
6+
const ans = [];
7+
dfs(root, 0, ans);
8+
return ans;
179
}
1810

1911
function dfs(root, level, ans) {
2012
if (!root) {
21-
return
13+
return;
2214
}
23-
ans[level] || (ans[level] = [])
24-
ans[level].push(root.val)
2515

26-
dfs(root.left, level + 1, ans)
27-
dfs(root.right, level + 1, ans)
16+
if (!ans[level]) {
17+
ans[level] = [];
18+
}
19+
20+
ans[level].push(root.val);
21+
dfs(root.left, level + 1, ans);
22+
dfs(root.right, level + 1, ans);
23+
return;
2824
}

0 commit comments

Comments
 (0)