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

Leaf-Similar Trees

binary trees · depth-first search · generators

Two binary trees are leaf-similar if reading their leaves from left to right produces the same sequence, regardless of how the trees are shaped above the leaves. Given two roots a and b, return True if they are leaf-similar.

Examples

      1          9
     / \        / \
    2   3      4   5
   /     \
  4       5

Input:  a = build_tree([1, 2, 3, 4, None, None, 5]), b = build_tree([9, 4, 5])
Output: True
Explanation: both leaf sequences are [4, 5].
Input:  a = build_tree([1, 2, 3, 4, None, None, 5]), b = build_tree([1, 5, 4])
Output: False
Explanation: [4, 5] versus [5, 4].

Constraints

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

Goals

  • Extract the left-to-right leaf sequence of a tree
  • Compare two sequences that may have different lengths
  • Reuse one helper for both trees
Starting Python…