InterviewPrepKit

Home / Coding / Trees

Leaf-Similar Trees

easy Original β†—
Solving tips
  • A left-to-right DFS visits leaves in exactly the required order β€” collect each tree's leaf values into a list and compare the two lists for equality. O(n1+n2) time.
  • For O(h) space with early exit, walk both trees with lazy leaf generators (or two explicit stacks) in lock-step and compare leaf by leaf.
  • Pitfall: don't compare concatenated strings ([12,3] and [1,23] both make '123') or sets (order and duplicates matter) β€” compare sequences.
  • Pitfall: in lock-step comparison use zip_longest or an explicit both-exhausted check, since plain zip would let a longer sequence pass; and push right-before-left in a stack version to keep left-to-right order.

Problem

Reading a binary tree’s leaves from left to right gives its leaf value sequence. Two trees are leaf-similar when their leaf value sequences are identical. Given the roots of two binary trees, root1 and root2, return True if they are leaf-similar, False otherwise.

The trees’ internal structure may differ arbitrarily β€” only the ordered list of leaf values matters.

Examples

Example 1

root1:        3                 root2:        3
            /   \                           /   \
           5     1                         5     1
          / \   / \                       / \   / \
         6   2 9   8                     6   7 4   2
            / \                                   / \
           7   4                                 9   8

Output: True

Both leaf sequences are [6, 7, 4, 9, 8] even though the shapes differ.

Example 2

root1: [1,2,3]      root2: [1,3,2]

    1                   1
   / \                 / \
  2   3               3   2

Output: False

Leaf sequences [2, 3] vs [3, 2] β€” same values, wrong order.

Constraints

  • Each tree has 1 to 200 nodes β€” tiny; clarity beats micro-optimization.
  • 0 <= Node.val <= 200 β€” duplicate values are possible, so compare sequences, not sets.

Think about it first

Hint 1 "Left to right over the leaves" is exactly the order a plain DFS visits them. What should you collect during that DFS?
Hint 2 Collect each tree's leaf values into a list and compare the two lists for equality. Watch out: comparing concatenated strings or sets breaks on cases like leaves `(12, 3)` vs `(1, 23)`.
Hint 3 For O(h) extra space instead of O(n): walk both trees simultaneously with two lazy leaf iterators (Python generators) and compare leaf by leaf, including detecting that both run out together.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.