DSA Factory
Free Trees lessonsTrees · Stage 6 · Views and widths · Step 1

What you see from the right

List the nodes visible when you look at a tree from its right side, which is the last node of each row, using the row-by-row walk. About 12 minutes.

One node per row

Imagine standing to the right of a tree and looking left. On each level, the node nearest to you hides all the others on that level. So you see exactly one node per level: the rightmost one.

It is not always the right child of the previous visible node. If the right side of the tree is shorter than the left, the visible node on a deep level lives on the left.

One per level: the rightmost node.
Not just right children: a left node can be visible.
In code
row = [1, 3, 4]
last = row[-1]
The right side view of the tree 5, 3, 6, 2, 4, none, 7, 1.
1234567
view
[5]

Row 1 has only 5, so 5 is visible.

Move 1 of 4

Find the last of each row

Use the row-by-row walk. At the start of each row, note how many nodes it has. While taking the row's nodes, remember the value of the one that was taken last, or compare the position to the row size minus one.

Add that value to the answer after the row. Reading the rows top to bottom gives the view from top to bottom. An empty tree has an empty view.

Row size: taken once at the start of the row.
Last position: is the row size minus one.
In code
for i in range(size):
    if i == size - 1:
        last = i      # the last in the row
Quick check

A level has the nodes 7, 4, 9 from left to right. Which one is visible from the right?

  1. A9, the last one
  2. B7, the first one
  3. CAll three
Show the answer

9, the last one. It is the rightmost node on the level.

Your problem

Binary tree right side view

Given the root of a binary tree, imagine standing on its right side. Return the values of the nodes you can see, ordered from top to bottom. A node is visible if no other node on its level lies to its right. An empty tree gives an empty list.

Example
root = [1, 2, 3, null, 5, null, 4] → [1, 3, 4]

0 ≤ number of nodes ≤ 100 · -100 ≤ node.val ≤ 100

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve