File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed
binary-tree-level-order-traversal Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * https://leetcode.com/problems/binary-tree-level-order-traversal/description/
3+ * Definition for a binary tree node.
4+ * function TreeNode(val, left, right) {
5+ * this.val = (val===undefined ? 0 : val)
6+ * this.left = (left===undefined ? null : left)
7+ * this.right = (right===undefined ? null : right)
8+ * }
9+ */
10+ /**
11+ * @param {TreeNode } root
12+ * @return {number[][] }
13+ */
14+ var levelOrder = function ( root ) {
15+ const result = [ ] ;
16+ if ( ! root ) return result ;
17+
18+ const queue = [ root ] ;
19+
20+ while ( queue . length > 0 ) {
21+ const levelSize = queue . length ;
22+ const level = [ ] ;
23+
24+ for ( let i = 0 ; i < levelSize ; i ++ ) {
25+ const node = queue . shift ( ) ;
26+ level . push ( node . val ) ;
27+
28+ if ( node . left ) queue . push ( node . left ) ;
29+ if ( node . right ) queue . push ( node . right ) ;
30+ }
31+
32+ result . push ( level ) ;
33+ }
34+
35+ return result ;
36+ } ;
You can’t perform that action at this time.
0 commit comments