Simple Java solution with BFS

  • 7
    public class Solution {
        public List<Integer> rightSideView(TreeNode root) {
            List<Integer> result = new ArrayList<Integer>();
            if(root==null) return result;
            Queue<TreeNode> q = new LinkedList<TreeNode>();
                int size = q.size();
                for(int i=0;i<size;i++){
                    TreeNode node= q.poll();
                    if(node.left!=null) q.add(node.left);
                    if(node.right!=null) q.add(node.right);
            return result;

  • 0

    so int size = q.size() is to store the number of nodes of current layer and then add to the result the very last one?

  • 0

    Yeah. This is needed because the size of the Queue changed during the loop execution. Since if you used i < q.size() in the loop, it would check that each time the loop iterated. If the size of the Queue increases during the loop execution then you would end up traversing more than a single level.

Log in to reply

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