shreyansh

Right View

Given the root of 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 1:

Screenshot 2024-06-08 at 12.42.10 PM.webp

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

class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> ans = new ArrayList<>();
        if(root == null) return ans;
        
        Queue<TreeNode> q = new LinkedList<>();
        q.add(root);

        while(!q.isEmpty()){
            int size = q.size();
            ans.add(q.peek().val);
            
            for(int i = 0; i < size; i++){
                TreeNode curr = q.poll();

                if(curr.right != null){
                    q.add(curr.right);
                }

                if(curr.left != null){
                    q.add(curr.left);
                }
            }
        }

        return ans;
    }
}