Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

Example:

Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:

   1            <---
 /   \
2     3         <---
 \     \
  5     4       <---

Solution

Perform Level Order traversal with simple condition

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public IList<int> RightSideView(TreeNode root) {
        
        var list = new List<int>();
        
        Queue<TreeNode> q = new Queue<TreeNode>();
        
        if(root == null)
            return list;
        
        q.Enqueue(root);
        
        while(q.Count > 0)
        {
            int size = q.Count;
            
            for(int i=0;i<size;i++)
            {
                TreeNode node = q.Dequeue();
                
                if(i == size-1)
                    list.Add(node.val);
                
                if(node.left != null)
                    q.Enqueue(node.left);
                
                if(node.right != null)
                    q.Enqueue(node.right);
            }
        }
        return list;
    }
}

Time Complexity: O(n)

Space Complexity: O(n)