InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Trees

Leaf-Similar Trees

easy Original ↗ 00:00

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.
  • 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. 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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug