File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed
binary-tree-level-order-traversal Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change
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
+ */
You can’t perform that action at this time.
0 commit comments