File tree Expand file tree Collapse file tree 1 file changed +14
-29
lines changed Expand file tree Collapse file tree 1 file changed +14
-29
lines changed Original file line number Diff line number Diff line change 12
12
* }
13
13
*/
14
14
public class Solution {
15
+ private List < int > _result = new ( ) ;
16
+
15
17
public IList < int > RightSideView ( TreeNode root ) {
16
- var result = new List < int > ( ) ;
17
- if ( root == null )
18
- return result ;
19
- var q = new Queue < TreeNode > ( ) ;
20
- q . Enqueue ( root ) ;
21
-
22
- // traverse the tree using BFS
23
- while ( true ) {
24
- var count = q . Count ;
25
- if ( count == 0 ) break ;
26
-
27
- for ( var i = 0 ; i < count ; i ++ ) {
28
- var cur = q . Dequeue ( ) ;
29
-
30
- if ( cur . left != null )
31
- q . Enqueue ( cur . left ) ;
32
- if ( cur . right != null )
33
- q . Enqueue ( cur . right ) ;
34
-
35
-
36
- // only add the last node from each level, i.e the rightmost node
37
- if ( i == count - 1 ) {
38
- result . Add ( cur . val ) ;
39
- }
40
- }
41
- }
42
-
43
- return result ;
18
+ Dfs ( root , 0 ) ;
19
+ return _result ;
44
20
}
45
- }
21
+
22
+ private void Dfs ( TreeNode root , int level ) {
23
+ if ( root == null ) return ;
24
+ if ( level >= _result . Count ) _result . Add ( root . val ) ;
25
+
26
+ // At first visit right node
27
+ Dfs ( root . right , level + 1 ) ;
28
+ Dfs ( root . left , level + 1 ) ;
29
+ }
30
+ }
You can’t perform that action at this time.
0 commit comments