AlgoTales · Roadmap

Right view

Intermediate · 8 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

The right view lists the last node on every level when you look at a tree from its right side. The trick is the same as the left view, mirrored, and it is a neat way to get "the latest" or "the outermost" item per layer.

Practical use cases

  • Web app: Latest reply at each depth of a thread. A support-ticket page shows replies branching under each other. A summary strip shows only the right-most, most recent reply on each level, so a manager can see where the conversation ended up. A thread of 400 messages is summarised in 6 lines.
  • Web app: Visible sidebar entries in a nested menu. A deeply nested sidebar menu is drawn flush to the right edge on narrow screens, and only the right-most item of each level has room to show an icon. The code picks the last node in each row so the icons never overlap. The menu stays tidy on small phones.
  • System: Skyline and visibility problems. Rendering engines for 2D scenes ask what is visible from one side of a stack of layers. The right view answers that kind of question quickly, and the same idea appears in map tools that need the outer edge of each row.

The story: The Balcony Watchers

The Sharma family's house had a staircase with a balcony on each floor. For the Holi party, guests stood on the balconies, a few on each floor. Raju stood on the right-hand side of the street and looked up at the building, wondering who he could see from there.

"On every balcony, I can only see the right-most guest," he said, "because the guests to their left are blocked by them." Mira wrote down the names: the right-most guest on floor one, on floor two, floor three, and so on.

Then Kabir found a twist. On the top floor, only one guest was standing, and she was at the left end of the balcony. But because nobody stood to her right, Raju could still see her from the street! "If you only watch the right edge of the building," said Mira, "you will miss her. Go floor by floor."

That list of names, one per floor, as seen from the right, is the right view of a tree. It uses the same floor-by-floor (level-order) walk, just picking the last person each time.

How to spot this problem, and where you need it

You need only the outermost, last or most recent entry from each layer of a tree-shaped structure, as seen from the right-hand side.

Signs you need it

  • The statement says "what is visible from the right", "last node of each level", or "rightmost value per row".
  • Your UI should show only one representative item per depth, and it must be the latest one.
  • You collected every node per level in lists and then took the last element of each list, wasting memory.

Where to use it in a project

  • Summary strips for nested conversations, where only the newest reply at each depth matters.
  • Edge detection when drawing layered diagrams or nested menus aligned to the right.

The solution

Walk level by level with a queue and, for each level, remember the last node processed. A second way is recursion that visits the right child before the left, and records a node the first time a new depth is reached. Either way, each level contributes exactly one value.

Payoff: Before: all 400 nodes returned and a client-side filter. After: only the 6 needed values, one per level, with no extra lists.

Explain it like I am 8

Stand on the right side of a tall building and look at its windows. On each floor, you only see the right-most window, because the others are further away behind it. The right view is the list of those right-most windows, floor by floor.

How it works, step by step

  1. Do the same level-order walk with a queue as for the left view.
  2. At the start of each level, save size, the number of nodes on this level.
  3. Go through the size nodes of this level from left to right, numbering them 0, 1, 2...
  4. The node numbered size - 1 (the last of the level) goes into the answer.
  5. Add children (left first, then right) for the next level. A recursive trick also works: go right first and record the first node you meet at each new depth.

The code in four languages

PHP

<?php
class TreeNode {
    public ?TreeNode $left = null;
    public ?TreeNode $right = null;
    public function __construct(public int $val) {}
}

// The example tree:      1
//                      /   \
//                     2     3
//                    / \     \
//                   4   5     6
//                      /
//                     7
function sampleTree(): TreeNode {
    $root = new TreeNode(1);
    $root->left = new TreeNode(2);
    $root->right = new TreeNode(3);
    $root->left->left = new TreeNode(4);
    $root->left->right = new TreeNode(5);
    $root->right->right = new TreeNode(6);
    $root->left->right->left = new TreeNode(7);
    return $root;
}

// Level by level (like BFS). Keep the last node of every level.
function rightView(?TreeNode $root): array {
    if ($root === null) return [];
    $view = [];
    $queue = [$root];
    while ($queue) {
        $size = count($queue);
        for ($i = 0; $i < $size; $i++) {
            $node = array_shift($queue);
            if ($i === $size - 1) $view[] = $node->val;   // last node of the level
            if ($node->left)  $queue[] = $node->left;
            if ($node->right) $queue[] = $node->right;
        }
    }
    return $view;
}

echo implode(' ', rightView(sampleTree())) . PHP_EOL;   // 1 3 6 7

JavaScript

class TreeNode {
  constructor(val) { this.val = val; this.left = null; this.right = null; }
}

// The example tree:      1
//                      /   \
//                     2     3
//                    / \     \
//                   4   5     6
//                      /
//                     7
function sampleTree() {
  const root = new TreeNode(1);
  root.left = new TreeNode(2);
  root.right = new TreeNode(3);
  root.left.left = new TreeNode(4);
  root.left.right = new TreeNode(5);
  root.right.right = new TreeNode(6);
  root.left.right.left = new TreeNode(7);
  return root;
}

// Level by level (like BFS). Keep the last node of every level.
function rightView(root) {
  if (root === null) return [];
  const view = [];
  const queue = [root];
  while (queue.length) {
    const size = queue.length;
    for (let i = 0; i < size; i++) {
      const node = queue.shift();
      if (i === size - 1) view.push(node.val);   // last node of the level
      if (node.left) queue.push(node.left);
      if (node.right) queue.push(node.right);
    }
  }
  return view;
}

console.log(rightView(sampleTree()).join(' '));   // 1 3 6 7

Java

import java.util.*;
import java.util.stream.*;

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

    // The example tree:      1
    //                       /   \
    //                      2     3
    //                     / \     \
    //                    4   5     6
    //                       /
    //                      7
    static TreeNode sampleTree() {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(4);
        root.left.right = new TreeNode(5);
        root.right.right = new TreeNode(6);
        root.left.right.left = new TreeNode(7);
        return root;
    }

    static String join(List<Integer> xs) {
        return xs.stream().map(String::valueOf).collect(Collectors.joining(" "));
    }

    // Level by level (like BFS). Keep the last node of every level.
    static List<Integer> rightView(TreeNode root) {
        List<Integer> view = new ArrayList<>();
        if (root == null) return view;
        Queue<TreeNode> queue = new ArrayDeque<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (i == size - 1) view.add(node.val);   // last node of the level
                if (node.left != null) queue.add(node.left);
                if (node.right != null) queue.add(node.right);
            }
        }
        return view;
    }

    public static void main(String[] args) {
        System.out.println(join(rightView(sampleTree())));   // 1 3 6 7
    }
}

Go

package main

import (
	"fmt"
	"strconv"
	"strings"
)

type TreeNode struct {
	Val         int
	Left, Right *TreeNode
}

// The example tree:      1
//
//	   /   \
//	  2     3
//	 / \     \
//	4   5     6
//	   /
//	  7
func sampleTree() *TreeNode {
	root := &TreeNode{Val: 1}
	root.Left = &TreeNode{Val: 2}
	root.Right = &TreeNode{Val: 3}
	root.Left.Left = &TreeNode{Val: 4}
	root.Left.Right = &TreeNode{Val: 5}
	root.Right.Right = &TreeNode{Val: 6}
	root.Left.Right.Left = &TreeNode{Val: 7}
	return root
}

// rightView goes level by level (like BFS). It keeps the last node of every level.
func rightView(root *TreeNode) []int {
	view := []int{}
	if root == nil {
		return view
	}
	queue := []*TreeNode{root}
	for len(queue) > 0 {
		size := len(queue)
		for i := 0; i < size; i++ {
			node := queue[0]
			queue = queue[1:]
			if i == size-1 {
				view = append(view, node.Val) // last node of the level
			}
			if node.Left != nil {
				queue = append(queue, node.Left)
			}
			if node.Right != nil {
				queue = append(queue, node.Right)
			}
		}
	}
	return view
}

// joinInts glues the numbers together with a separator.
func joinInts(xs []int, sep string) string {
	parts := make([]string, len(xs))
	for i, v := range xs {
		parts[i] = strconv.Itoa(v)
	}
	return strings.Join(parts, sep)
}

func main() {
	fmt.Println(joinInts(rightView(sampleTree()), " ")) // 1 3 6 7
}

Time: O(n) · Extra space: O(w). Every node enters the queue once; the queue never holds more than the widest level (w).

Watch out for

  • Only walking down node.right. That stops where the right side ends and misses deeper levels (like the 7 here).
  • Mixing up the index: for the right view you need the last node of each level, which is size - 1, not 0.
  • Not saving size before the inner loop, so the loop bound keeps changing as children are added.

Quick check

  1. What is the right view of our example tree?
    • 7 6 3 1
    • 1 3 6
    • 1 2 5 7
    • 1 3 6 7
  2. In the level-order loop, which index is the right view node?
    • size / 2
    • 0
    • size - 1
  3. For this tree, are the left view and the right view the same?
    • Yes, always
    • No: they are 1 2 4 7 and 1 3 6 7
    • Only for balanced trees