Problem 423439 · easy · Phase 04 Non-Linear Data Structures

Leaf Sequence

binary trees · traversal · leaf nodes

Given the root of a binary tree, return the values of its leaves from left to right (the order in which they would appear if you traced the bottom edge of the drawing).

Examples

      1
     / \
    2   3
   / \   \
  4   5   6

Input:  root = build_tree([1, 2, 3, 4, 5, None, 6])
Output: [4, 5, 6]
    3
   / \
  9  20
     / \
    15  7

Input:  root = build_tree([3, 9, 20, None, None, 15, 7])
Output: [9, 15, 7]

Constraints

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

Goals

  • Collect leaves in left-to-right order
  • Choose a traversal order that visits leaves left to right
  • Return an empty list for an empty tree
Starting Python…