A simple solution with level-order


  • 0
    L

    I couldn't visualize to solve it using a recursive solution. I opted for a solution that uses level order by pushing the right-most child first at each level. The idea is to pick the first element at each level from the queue so if right child is not available, it will use whatever is there.

    import java.util.*;
    public class Solution {
        public List<Integer> rightSideView(TreeNode root) {
            List<Integer> list = new LinkedList<>();
            if(root==null) {
                return list;
            }
            Deque<TreeNode> queue = new LinkedList<>();
            queue.add(root);
            while(!queue.isEmpty()) {
                int level = queue.size();
                list.add(queue.peek().val);
                while(level>0) {
                    TreeNode node = queue.poll();
                    if(node.right!=null) {
                        queue.add(node.right);
                    }
                    if(node.left!=null) {
                        queue.add(node.left);
                    }
                    level--;
                }
            }
    
        return list;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.