Skip to content

Commit 14ef09a

Browse files
committed
solve: binary tree level order traversal
1 parent 16d9ab3 commit 14ef09a

File tree

1 file changed

+37
-0
lines changed
  • binary-tree-level-order-traversal

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* @param {TreeNode} root
3+
* @return {number[][]}
4+
*/
5+
var levelOrder = function (root) {
6+
const result = [];
7+
8+
const dfs = (node, level) => {
9+
if (!node) {
10+
return;
11+
}
12+
13+
if (!result[level]) {
14+
result[level] = [];
15+
}
16+
17+
result[level].push(node.val);
18+
19+
dfs(node.left, level + 1);
20+
dfs(node.right, level + 1);
21+
};
22+
23+
dfs(root, 0);
24+
25+
return result;
26+
};
27+
28+
/**
29+
* Time Complexity: O(n)
30+
* - The function visits each node exactly once, making it O(n).
31+
* - Here, n is the number of nodes in the binary tree.
32+
*
33+
* Space Complexity: O(n)
34+
* - The space complexity is determined by the recursion stack.
35+
* - In the worst case, the recursion stack could store all nodes in the binary tree.
36+
* - Thus, the space complexity is O(n).
37+
*/

0 commit comments

Comments
 (0)