Binary Tree Right Side View

Return the value you see on each level of a binary tree when you look at it from the right side.

A binary tree is made of nodes. Each node holds a value and points to at most two children, a left child and a right child, and the node at the top is called the root. Given the root of a binary tree, imagine standing to its right and looking at it. Return the values of the nodes you can see, from top to bottom.

In the examples, a tree is written as a list of values row by row, from left to right, with null where a node has no child in that place.

Example 1
Input: root = [1, 2, 3, null, 5, null, 4]
Output: [1, 3, 4]
Example 2
Input: root = [1, 2, 3, 4]
Output: [1, 3, 4]
Explanation: 4 is the left child of 2, but nothing is to its right, so it is visible.
Solution

The Idea

Think of a tree drawn on a page, with the root at the top and its children one row below. Each row is called a level: the root alone is level 0, its children are level 1, their children are level 2, and so on. Standing to the right of the page, you look along each level, and the node nearest to you hides the rest of that level.

Look at the picture below. On the left is Example 1, drawn level by level. Level 0 holds only 1. Level 1 holds 2 and 3, and from the right you see 3. Level 2 holds 5 and 4, and you see 4. That gives [1, 3, 4].

The two example trees drawn level by level, with an arrow from the right to the node seen on each level. In Example 1 the arrows reach 1, 3 and 4. In Example 2 they reach 1, 3 and 4 as well, where 4 is the left child of 2 and nothing is to the right of 4.

In Example 1, every node you see is a right child: 3 is the right child of 1, and 4 is the right child of 3. So is the answer simply the path you get by going right again and again from the root?

Example 2, on the right of the picture, says no. Going right from 1 reaches 3, and 3 has no children, so that path stops after two values. Yet level 2 still holds a node: 4, the left child of 2. The arrow on level 2 crosses the empty space marked "nothing to the right of 4" and reaches it, so 4 is seen too.

So the node you see on a level does not depend on which parent it hangs from. It is the last node of that level, read from left to right. The problem becomes: visit the tree one level at a time, and keep the last value of each level.

Solution Approach

Turning that idea into code means settling two things: how to visit the nodes level by level, and how to tell which node is the last one on its level. First, though, a look at why only going right falls short, and at the end an optional walk that goes deep first.

Following right children only

Why not start at the root and keep going to the right child, collecting every value on the way? It is short, and it works for Example 1. For Example 2 it returns [1, 3]: it stops at 3, which has no children, and never reaches 4 on level 2. Any level whose last node sits under a left branch is missed.

Visiting the tree level by level

How can we read the nodes one level at a time, left to right? With a queue: a line where items join at the back and leave from the front. Put the root in it. Then, again and again, take the node at the front and add its left child and its right child at the back.

The children always join behind every node still waiting, so the queue hands out all of level 0, then all of level 1, then all of level 2. Visiting a tree in this order is called breadth-first search, because it covers the whole width of a level before going deeper. It is also called a level order traversal.

Finding the last node of each level

The queue mixes levels, though: while level 1 is being taken out, level 2 is already joining at the back. Where does one level end? Look at the queue before taking any node of a level. At that moment it holds exactly that level and nothing else, so its size tells how many nodes the level has.

Take exactly that many nodes in one round, and the last one taken is the node seen from the right. In Example 2, the round for level 1 starts with 2 and 3 in the queue, so it takes two nodes. Taking 2 adds 4 at the back, and 3, the second and last node of the round, is recorded. The next round starts with only 4 in the queue, so 4 is recorded.

A depth-first alternative (optional)

A walk can also go deep first: from each node, go all the way down its right child before turning to its left child, and pass along the level number. The first node reached on each new level is the one seen from the right. Written as a method that calls itself for each child, it keeps one unfinished call per level above the current node, so its memory grows with the number of levels, not the widest level. It gives the same answers for both examples.

Java Solution

The method rightSideView works in these steps:

  1. First, create the list view for the answer and an ArrayDeque, a Java queue backed by an array, named queue. Put root in the queue only if it is not null, so an empty tree skips the loops and returns an empty list.
  2. Run a while loop, one round per level, as long as queue has nodes. At the start of each round, store queue.size() in size: the number of nodes on this level.
  3. Inside, a for loop takes size nodes from the front with poll(), counting them with i. When i == size - 1, the node is the last of its level, so add node.val to view.
  4. For every node taken, add its left child and then its right child to the back of queue, if they exist. They wait there for the next round.
  5. When the queue is empty, every level has been visited, and view holds one value per level, and the method returns it.

The class also has a small TreeNode class and a build helper that makes a tree from a list written like the examples. The main method runs both examples, an empty tree, a tree of one node, and the tree [1, 2, 3, 4, null, null, null, 5], whose two deepest levels both sit under the left branch.

Java
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

public class BinaryTreeRightSideView {

    static class TreeNode {
        int val;
        TreeNode left, right;
        TreeNode(int val) { this.val = val; }
    }

    public static List<Integer> rightSideView(TreeNode root) {
        List<Integer> view = new ArrayList<>();
        Queue<TreeNode> queue = new ArrayDeque<>();
        if (root != null) {
            queue.add(root);
        }
        while (!queue.isEmpty()) {
            int size = queue.size();              // nodes on the current level
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (i == size - 1) {
                    view.add(node.val);           // the last node of the level is the one seen
                }
                if (node.left != null) {
                    queue.add(node.left);         // children wait for the next round
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
            }
        }
        return view;
    }

    // Builds a tree from values listed level by level, left to right, null for no node.
    static TreeNode build(Integer... values) {
        if (values.length == 0 || values[0] == null) {
            return null;
        }
        TreeNode root = new TreeNode(values[0]);
        Queue<TreeNode> parents = new ArrayDeque<>();
        parents.add(root);
        int k = 1;
        while (k < values.length) {
            TreeNode parent = parents.poll();
            if (values[k] != null) {
                parent.left = new TreeNode(values[k]);
                parents.add(parent.left);
            }
            k++;
            if (k < values.length && values[k] != null) {
                parent.right = new TreeNode(values[k]);
                parents.add(parent.right);
            }
            k++;
        }
        return root;
    }

    public static void main(String[] args) {
        System.out.println(rightSideView(build(1, 2, 3, null, 5, null, 4)));
        System.out.println(rightSideView(build(1, 2, 3, 4)));
        System.out.println(rightSideView(build()));
        System.out.println(rightSideView(build(7)));
        System.out.println(rightSideView(build(1, 2, 3, 4, null, null, null, 5)));
    }
}

Running it prints:

Output
[1, 3, 4]
[1, 3, 4]
[]
[7]
[1, 3, 4, 5]

Both examples give [1, 3, 4]. In the second, 4 is recorded even though it is a left child, because the round for level 2 holds only 4, so size is 1 and 4 is at position 0, the last one.

The empty tree prints [], since the root never enters the queue, and the single node 7 is its own level. Look at the last line, [1, 3, 4, 5]: 4 is the left child of 2, and 5 is the left child of 4. Going right from the root would stop at [1, 3], while the queue still finds one node on each of the four levels.

Complexity

The work is one trip through the queue for each node, and the memory is mostly the queue itself.

  • Time: O(n), for a tree of n nodes, because each node joins the queue once and leaves it once. In between there is only a fixed amount of work: one position check and two child checks.
  • Space: O(w), where w is the largest number of nodes on one level. The queue holds what is left of the current level plus the children already added for the next one. In a tree where every level is filled, the bottom level holds about half of all the nodes. The answer adds one value per level.

The same round-by-round loop, keeping every value of a level instead of the last, gives Level Order Traversal.