File tree 3 files changed +39
-27
lines changed
solution/0100-0199/0199.Binary Tree Right Side View
3 files changed +39
-27
lines changed Original file line number Diff line number Diff line change @@ -213,19 +213,23 @@ func rightSideView(root *TreeNode) (ans []int) {
213
213
*/
214
214
215
215
function rightSideView(root : TreeNode | null ): number [] {
216
- const ans = [];
217
216
if (! root ) {
218
- return ans ;
217
+ return [] ;
219
218
}
220
- const q = [root ];
219
+ let q = [root ];
220
+ const ans: number [] = [];
221
221
while (q .length ) {
222
- const n = q .length ;
223
- ans .push (q [n - 1 ].val );
224
- for (let i = 0 ; i < n ; ++ i ) {
225
- const { left, right } = q .shift ();
226
- left && q .push (left );
227
- right && q .push (right );
222
+ const nextq: TreeNode [] = [];
223
+ ans .push (q .at (- 1 )! .val );
224
+ for (const { left, right } of q ) {
225
+ if (left ) {
226
+ nextq .push (left );
227
+ }
228
+ if (right ) {
229
+ nextq .push (right );
230
+ }
228
231
}
232
+ q = nextq ;
229
233
}
230
234
return ans ;
231
235
}
Original file line number Diff line number Diff line change @@ -203,19 +203,23 @@ func rightSideView(root *TreeNode) (ans []int) {
203
203
*/
204
204
205
205
function rightSideView(root : TreeNode | null ): number [] {
206
- const ans = [];
207
206
if (! root ) {
208
- return ans ;
207
+ return [] ;
209
208
}
210
- const q = [root ];
209
+ let q = [root ];
210
+ const ans: number [] = [];
211
211
while (q .length ) {
212
- const n = q .length ;
213
- ans .push (q [n - 1 ].val );
214
- for (let i = 0 ; i < n ; ++ i ) {
215
- const { left, right } = q .shift ();
216
- left && q .push (left );
217
- right && q .push (right );
212
+ const nextq: TreeNode [] = [];
213
+ ans .push (q .at (- 1 )! .val );
214
+ for (const { left, right } of q ) {
215
+ if (left ) {
216
+ nextq .push (left );
217
+ }
218
+ if (right ) {
219
+ nextq .push (right );
220
+ }
218
221
}
222
+ q = nextq ;
219
223
}
220
224
return ans ;
221
225
}
Original file line number Diff line number Diff line change 13
13
*/
14
14
15
15
function rightSideView ( root : TreeNode | null ) : number [ ] {
16
- const ans = [ ] ;
17
16
if ( ! root ) {
18
- return ans ;
17
+ return [ ] ;
19
18
}
20
- const q = [ root ] ;
19
+ let q = [ root ] ;
20
+ const ans : number [ ] = [ ] ;
21
21
while ( q . length ) {
22
- const n = q . length ;
23
- ans . push ( q [ n - 1 ] . val ) ;
24
- for ( let i = 0 ; i < n ; ++ i ) {
25
- const { left, right } = q . shift ( ) ;
26
- left && q . push ( left ) ;
27
- right && q . push ( right ) ;
22
+ const nextq : TreeNode [ ] = [ ] ;
23
+ ans . push ( q . at ( - 1 ) ! . val ) ;
24
+ for ( const { left, right } of q ) {
25
+ if ( left ) {
26
+ nextq . push ( left ) ;
27
+ }
28
+ if ( right ) {
29
+ nextq . push ( right ) ;
30
+ }
28
31
}
32
+ q = nextq ;
29
33
}
30
34
return ans ;
31
35
}
You can’t perform that action at this time.
0 commit comments