Editor

Right Side View

#95 · Trees · Intermediate · 75 XP · about 12 min

Imagine standing to the right of a binary tree and looking at it. On each level you see only the rightmost node, and the others hide behind it. Write right_view(root) that returns the values you can see, from the top level to the bottom. An empty tree gives [].

Each node is a Node with a value val and two children, left and right, which are None when missing. The provided build makes a tree from a list of values in level order, where None marks a missing child.

Examples

    8
   / \
  3   10
   \    \
    6    14
right_view(build([8, 3, 10, None, 6, None, 14]))  # returns [8, 10, 14]
right_view(build([8, 3, 10, 1]))  # returns [8, 10, 1]
right_view(build([]))  # returns []

The drawing shows the first tree. In the second example the bottom level holds only the node 1, a left child, but nothing stands in front of it, so you still see it.

Constraints

  • 0 to 2,000 nodes; values are integers.

Ready?

Accept the challenge to start writing. A small timer counts the time this page is in view.

Output appears here.