Ctrl K

The Tree Seen From the Right

Medium
You are given the root of a binary tree. Picture yourself standing to the right of the drawn tree and looking at it. On each level you see exactly one node: the one closest to you, which is the rightmost node of that level and hides all the others. Return the values of the visible nodes from top to bottom. For an empty tree, return an empty list.
Example 1
root=tree_node([7, 2, 9, 4, 6, None, 1]) → [7, 9, 1]

On every level the rightmost node is the visible one: 7, then 9, then 1.

Example 2
root=tree_node([1, 2, 3, 4]) → [1, 3, 4]

The third level holds only 4. It hangs on the left, but nothing on that level is further right, so it is visible too.

Example 3
root=tree_node([]) → []

An empty tree shows nothing.

Constraints
  • 0 ≤ number of nodes ≤ 1000
  • -1000 ≤ Node.val ≤ 1000
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsTree Columns, Top Down MediumFirst Value on the Lowest Row MediumLargest Value on Each Tree Level MediumInsert a Tree Level MediumA Tree Drawn on a Grid Medium
loading Python…
Input
root=tree_node([7, 2, 9, 4, 6, None, 1])
Expected
[7, 9, 1]

Run checks the first 3 tests in your browser. Submit checks all 96 tests on the server, hidden ones included.