Java solution BFS with a Queue

  • 0

    This solution travels through the whole tree in BFS. For every level, add nodes' children into queue in first-left-then-right order, so the end node of every level is what we want.

    public class Solution {
        public List<Integer> rightSideView(TreeNode root) {
            List<Integer> result = new ArrayList<Integer>();
            Queue<TreeNode> order = new LinkedList<TreeNode>();
            if (root == null) return result;
            while(!order.isEmpty()) {
                int count = order.size();
                //Every level begins
                while(count > 0) {
                    TreeNode node = order.poll();
                    if (node.left != null) order.offer(node.left);
                    if (node.right != null) order.offer(node.right);
                    if (--count == 0) {
            return result;

Log in to reply

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