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
In the examples, a tree is written as a list of values row by row, from left to right, with null
Example 1
Output: [1, 3, 4]
Example 2
Output: [1, 3, 4]
Explanation: 4 is the left child of 2, but nothing is to its right, so it is visible.
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]
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]
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
- First, create the list
for the answer and anview , a Java queue backed by an array, namedArrayDeque . Putqueue in the queue only if it is notroot , so an empty tree skips the loops and returns an empty list.null - Run a
loop, one round per level, as long aswhile has nodes. At the start of each round, storequeue inqueue.size() : the number of nodes on this level.size - Inside, a
loop takesfor nodes from the front withsize , counting them withpoll() . Wheni , the node is the last of its level, so addi == size - 1 tonode.val .view - For every node taken, add its left child and then its right child to the back of
, if they exist. They wait there for the next round.queue - When the queue is empty, every level has been visited, and
holds one value per level, and the method returns it.view
The class also has a small TreeNodebuildmain[1, 2, 3, 4, null, null, null, 5]
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:
[1, 3, 4]
[1, 3, 4]
[]
[7]
[1, 3, 4, 5]
Both examples give [1, 3, 4]size
The empty tree prints [][1, 3, 4, 5][1, 3]
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