Copy **Input:** root = [1,2,3,null,5,null,4]
**Output:** [1,3,4]
Copy **Input:** root = [1,null,3]
**Output:** [1,3]
Copy **Input:** root = []
**Output:** []
Copy /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List < Integer > rightSideView ( TreeNode root) {
List < Integer > res = new ArrayList < Integer >();
if (root == null ) return res;
Queue < TreeNode > q = new LinkedList < TreeNode >();
q . offer (root);
while ( ! q . isEmpty ()) {
int len = q . size ();
for ( int i = 0 ; i < len; i ++ ) {
TreeNode curr = q . poll ();
if ( curr . left != null ) q . offer ( curr . left );
if ( curr . right != null ) q . offer ( curr . right );
if (i == len - 1 ) res . add ( curr . val );
}
}
return res;
}
}
Copy class Solution {
public List < Integer > rightSideView ( TreeNode root) {
List < Integer > res = new ArrayList < Integer >();
helper(root , res , 0 ) ;
return res;
}
private void helper ( TreeNode root , List < Integer > res , int currDepth) {
if (root == null ) return ;
if (currDepth >= res . size ()) res . add ( root . val );
helper( root . right , res , currDepth + 1 ) ;
helper( root . left , res , currDepth + 1 ) ;
}
}