File tree Expand file tree Collapse file tree 1 file changed +50
-0
lines changed
Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Original file line number Diff line number Diff line change @@ -19,3 +19,53 @@ return its level order traversal as:
1919 [15,7]
2020]
2121*/
22+
23+ /**
24+ * Definition for a binary tree node.
25+ * function TreeNode(val) {
26+ * this.val = val;
27+ * this.left = this.right = null;
28+ * }
29+ */
30+ /**
31+ * @param {TreeNode } root
32+ * @return {number[][] }
33+ */
34+ var levelOrder = function ( root ) {
35+ var result = [ ] ;
36+
37+ if ( root === null ) {
38+ return result ;
39+ }
40+
41+ var queue = [ ] ;
42+ var temp = [ ] ;
43+ var curLvlCnt = 1 ;
44+ var nextLvlCnt = 0 ;
45+
46+ queue . push ( root ) ;
47+
48+ while ( queue . length !== 0 ) {
49+ var p = queue . shift ( ) ;
50+ temp . push ( p . val ) ;
51+ curLvlCnt -- ;
52+
53+ if ( p . left ) {
54+ queue . push ( p . left ) ;
55+ nextLvlCnt ++ ;
56+ }
57+ if ( p . right ) {
58+ queue . push ( p . right ) ;
59+ nextLvlCnt ++ ;
60+ }
61+
62+ if ( curLvlCnt === 0 ) {
63+ result . push ( temp ) ;
64+ curLvlCnt = nextLvlCnt ;
65+ nextLvlCnt = 0 ;
66+ temp = [ ] ;
67+ }
68+ }
69+
70+ return result ;
71+ } ;
You can’t perform that action at this time.
0 commit comments