Problem 413505 · medium · Level 04 Non-Linear Data Structures

Lamps Seen From the East Window

binary trees · breadth-first search · level tracking

A binary tree of lamps is drawn with the root at the top and one level per row. Seen through a window on the east (right-hand) side, the lamp furthest to the right on each row hides the rest of that row. Given the root, return the value of the rightmost node on every level, from the top level down.

Examples

      8
     / \
    3   6
   / \
  2   7
     /
    4

Input:  root = build_tree([8, 3, 6, 2, 7, None, None, None, None, 4])
Output: [8, 6, 7, 4]
Explanation: on the third level nothing stands to the right of 7, so it shows.
    1
   /
  2
 /
3

Input:  root = build_tree([1, 2, None, 3])
Output: [1, 2, 3]
Explanation: nothing hides the left chain, so every node is visible.

Constraints

  • 0 <= number of nodes <= 2000
  • -10**4 <= node.val <= 10**4
  • Target complexity: O(n) time.

Goals

  • Identify the last node of every level
  • Understand that a left-subtree node can be visible when the right subtree is shorter
  • Return values from top to bottom
Starting Python…