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

Right Side View

binary trees · breadth-first search · level tracking

Stand to the right of a binary tree and look at it: on every level you see only the rightmost node. Given the root, return the values you see, ordered from top to bottom.

Examples

    1
   / \
  2   3
   \   \
    5   4

Input:  root = build_tree([1, 2, 3, None, 5, None, 4])
Output: [1, 3, 4]
    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…