AlgoInsight

DSA problem

Binary Tree Right Side View

MediumTree Traversal - Level OrderPattern: Tree Traversal - Level Ordertop75AmazonMetaMicrosoftGoogleBloomberg

Given the root of a binary tree, imagine yourself standing on the right side of it. Return the values of the nodes you can see, ordered from top to bottom. A node is visible from the right if it is the rightmost node at its depth — any other node at the same depth that lies to its left is obscured by it.

The natural insight is that the right-side view is exactly the last value seen at each level when we traverse the tree level by level from left to right. So a standard BFS already collects each level's values in left-to-right order; the rightmost value of that level is simply the last element of the per-level list.

A small optimisation avoids building the full per-level list at all: while dequeuing the level_size nodes of the current level, simply record the value of the LAST one (i.e. the node dequeued at iteration level_size - 1). This trims the per-level memory to a single integer.

An alternative DFS approach traverses the tree right-first and records a node's value the first time the DFS reaches a new depth (depth equals the current result length). Both run in O(n) time. BFS uses O(w) extra space; DFS uses O(h) recursion stack. Since this problem belongs to the level-order pattern, the canonical solution we present here is BFS.

Examples

Example 1
Input: root = [1,2,3,null,5,null,4]
Output: [1,3,4]
Explanation: Level 0 sees the root 1. Level 1 sees 3 (the rightmost of [2,3]). Level 2 sees 4 (the rightmost of [5,4]).
Example 2
Input: root = [1,null,3]
Output: [1,3]
Explanation: A right-skewed tree shows the head of each level: the root then its right child.
Example 3
Input: root = []
Output: []
Explanation: An empty tree shows no nodes.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

binary-treebfslevel-orderdfs

Browse all DSA problems