InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Trees

Binary Tree Right Side View

medium Original ↗ 00:00

Problem

You are given the root of a binary tree. Imagine standing to the right of the tree and looking left. Return the values of the nodes you can see, ordered from top to bottom.

In other words, for each depth level of the tree, the visible node is the rightmost one at that level. Return one value per level.

Examples

Example 1

Input: root = [1,2,3,null,5,null,4]
Output: [1,3,4]

Level 0: 1. Level 1: nodes 2,3 — rightmost is 3. Level 2: nodes 5,4 — rightmost is 4.

Example 2

Input: root = [1,null,3]
Output: [1,3]

The root 1 has only a right child 3; both are visible from the right.

Example 3

Input: root = [1,2,3,4]
Output: [1,3,4]

Level 0: 1. Level 1: 2,33. Level 2: only node 4 (left child of 2), so it is the rightmost by default.

Constraints

  • The number of nodes is in the range [0, 100].
  • -100 <= Node.val <= 100
  • An empty tree returns an empty list.

Think about it first

Hint 1 The visible node at each depth is the last node you would encounter scanning that level from left to right. So this is really "grab the last node of every level."
Hint 2 A breadth-first (level-order) traversal processes the tree one level at a time. If you know how many nodes are in the current level, the last one you dequeue is the rightmost.
Hint 3 Alternatively, do a DFS that visits the right child before the left, and record a node's value only the first time you reach a new depth — the first node seen at each depth from a right-first DFS is the rightmost one.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug