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
+ // ✅ Time Complexity: O(n), where n is the number of nodes in the tree
2
+ // ✅ Space Complexity: O(n)
3
+
4
+ /**
5
+ * Definition for a binary tree node.
6
+ * function TreeNode(val, left, right) {
7
+ * this.val = (val===undefined ? 0 : val)
8
+ * this.left = (left===undefined ? null : left)
9
+ * this.right = (right===undefined ? null : right)
10
+ * }
11
+ */
12
+ /**
13
+ * @param {TreeNode } root
14
+ * @return {number[][] }
15
+ */
16
+ var levelOrder = function ( root ) {
17
+ if ( ! root ) return [ ] ;
18
+
19
+ let output = [ ] ;
20
+ let queue = [ root ] ;
21
+
22
+ while ( queue . length > 0 ) {
23
+ let values = [ ] ;
24
+
25
+ const lengthQueue = queue . length ;
26
+
27
+ for ( let i = 0 ; i < lengthQueue ; i ++ ) {
28
+ const node = queue . shift ( ) ;
29
+ values . push ( node . val ) ;
30
+ if ( node . left ) queue . push ( node . left ) ;
31
+ if ( node . right ) queue . push ( node . right ) ;
32
+ }
33
+ output . push ( values ) ;
34
+ }
35
+ return output ;
36
+ } ;
37
+
You can’t perform that action at this time.
0 commit comments