File tree Expand file tree Collapse file tree 1 file changed +67
-0
lines changed
binary-tree-level-order-traversal Expand file tree Collapse file tree 1 file changed +67
-0
lines changed Original file line number Diff line number Diff line change 1+ // n: number of nodes
2+ // Time complexity: O(n)
3+ // Space complexity: O(n)
4+
5+ class _Queue {
6+ constructor ( ) {
7+ this . q = [ ] ;
8+ this . front = 0 ;
9+ this . rear = 0 ;
10+ }
11+
12+ push ( value ) {
13+ this . q . push ( value ) ;
14+ this . rear ++ ;
15+ }
16+
17+ shift ( ) {
18+ const rv = this . q [ this . front ] ;
19+ delete this . q [ this . front ++ ] ;
20+ return rv ;
21+ }
22+
23+ isEmpty ( ) {
24+ return this . front === this . rear ;
25+ }
26+ }
27+
28+ /**
29+ * Definition for a binary tree node.
30+ * function TreeNode(val, left, right) {
31+ * this.val = (val===undefined ? 0 : val)
32+ * this.left = (left===undefined ? null : left)
33+ * this.right = (right===undefined ? null : right)
34+ * }
35+ */
36+ /**
37+ * @param {TreeNode } root
38+ * @return {number[][] }
39+ */
40+ var levelOrder = function ( root ) {
41+ const answer = [ ] ;
42+ const q = new _Queue ( ) ;
43+
44+ if ( root ) {
45+ q . push ( [ root , 0 ] ) ;
46+ }
47+
48+ while ( ! q . isEmpty ( ) ) {
49+ const [ current , lv ] = q . shift ( ) ;
50+
51+ if ( answer . at ( lv ) === undefined ) {
52+ answer [ lv ] = [ ] ;
53+ }
54+
55+ answer [ lv ] . push ( current . val ) ;
56+
57+ if ( current . left ) {
58+ q . push ( [ current . left , lv + 1 ] ) ;
59+ }
60+
61+ if ( current . right ) {
62+ q . push ( [ current . right , lv + 1 ] ) ;
63+ }
64+ }
65+
66+ return answer ;
67+ } ;
You can’t perform that action at this time.
0 commit comments