File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed
binary-tree-level-order-traversal Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Time Complexity: O(n)
2
+ // Space Complexity: O(n)
3
+
4
+ var levelOrder = function ( root ) {
5
+ // if the root is null, return an empty array.
6
+ if ( root === null ) return [ ] ;
7
+
8
+ const result = [ ] ;
9
+ const queue = [ root ] ;
10
+
11
+ // while there are nodes in the queue,
12
+ while ( queue . length > 0 ) {
13
+ const levelSize = queue . length ;
14
+ const currentLevel = [ ] ;
15
+
16
+ // loop nodes in the current level.
17
+ for ( let i = 0 ; i < levelSize ; i ++ ) {
18
+ // dequeue the front node.
19
+ const currentNode = queue . shift ( ) ;
20
+ // add value to the current level array.
21
+ currentLevel . push ( currentNode . val ) ;
22
+ // enqueue left child if exists.
23
+ if ( currentNode . left ) queue . push ( currentNode . left ) ;
24
+ // enqueue right child if exists.
25
+ if ( currentNode . right ) queue . push ( currentNode . right ) ;
26
+ }
27
+
28
+ // add the current level array to the result.
29
+ result . push ( currentLevel ) ;
30
+ }
31
+
32
+ return result ;
33
+ } ;
You can’t perform that action at this time.
0 commit comments