24
24
25
25
public class _199 {
26
26
27
- public List <Integer > rightSideView (TreeNode root ) {
28
- List <Integer > result = new ArrayList <>();
29
- if (root == null ) {
27
+ public static class Solution1 {
28
+ /**credit: https://leetcode.com/problems/binary-tree-right-side-view/discuss/56012/My-simple-accepted-solution(JAVA)*/
29
+ public List <Integer > rightSideView (TreeNode root ) {
30
+ List <Integer > result = new ArrayList <>();
31
+ rightView (root , result , 0 );
30
32
return result ;
31
33
}
32
- Queue <TreeNode > q = new LinkedList <>();
33
- q .offer (root );
34
- while (!q .isEmpty ()) {
35
- int size = q .size ();
36
- for (int i = 0 ; i < size ; i ++) {
37
- TreeNode curr = q .poll ();
38
- if (i == size - 1 ) {
39
- result .add (curr .val );
40
- }
41
- if (curr .left != null ) {
42
- q .offer (curr .left );
43
- }
44
- if (curr .right != null ) {
45
- q .offer (curr .right );
34
+
35
+ void rightView (TreeNode curr , List <Integer > result , int currDepth ) {
36
+ if (curr == null ) {
37
+ return ;
38
+ }
39
+ if (currDepth == result .size ()) {
40
+ result .add (curr .val );
41
+ }
42
+ rightView (curr .right , result , currDepth + 1 );
43
+ rightView (curr .left , result , currDepth + 1 );
44
+ }
45
+ }
46
+
47
+ public static class Solution2 {
48
+ /**BFS the tree*/
49
+ public List <Integer > rightSideView (TreeNode root ) {
50
+ List <Integer > result = new ArrayList <>();
51
+ if (root == null ) {
52
+ return result ;
53
+ }
54
+ Queue <TreeNode > q = new LinkedList <>();
55
+ q .offer (root );
56
+ while (!q .isEmpty ()) {
57
+ int size = q .size ();
58
+ for (int i = 0 ; i < size ; i ++) {
59
+ TreeNode curr = q .poll ();
60
+ if (i == size - 1 ) {
61
+ result .add (curr .val );
62
+ }
63
+ if (curr .left != null ) {
64
+ q .offer (curr .left );
65
+ }
66
+ if (curr .right != null ) {
67
+ q .offer (curr .right );
68
+ }
46
69
}
47
70
}
71
+ return result ;
48
72
}
49
- return result ;
50
73
}
51
74
52
75
}
0 commit comments