A leaf is a node with no children. List the leaf values of a tree in order, leftmost leaf first, and you have its leaf sequence.
You get the roots of two binary trees, root1 and root2. Return true if their leaf sequences are exactly the same, and false otherwise. The shapes and the values of the other nodes do not matter.
Example 1
Input: root1 = [5, 3, 8, 1, 4], root2 = [6, 1, 2, null, null, 4, 8] Output: true Why: both leaf sequences are 1, 4, 8
2 more examples and the constraints
Example 2
Input: root1 = [2, 5, 9], root2 = [2, 9, 5] Output: false Why: 5, 9 is not the same order as 9, 5
Example 3
Input: root1 = [3, 1], root2 = [1] Output: true Why: each tree has a single leaf, 1
Constraints
- 1 ≤ number of nodes in each tree ≤ 200
- 0 ≤ each node value ≤ 200
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Collect both leaf listsO(n1 + n2)
- Two stacks, one leaf at a timeO(n1 + n2)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Extra memory for two trees of 200 nodes | Verdict |
|---|---|---|---|
| Collect both leaf lists | O(n1 + n2) | Passes; stores every leaf | |
| Two stacks, one leaf at a time | O(n1 + n2) | Best; stops at the first mismatch |
n1, n2 = nodes in each tree; h1, h2 = their heights.
Edge cases to test
- Same leaves, other order. [2, 5, 9] and [2, 9, 5] both have leaves 5 and 9, but in a different order: false.
- One sequence is a prefix. Leaves 2, 3 against 2, 3, 4 must be false; check that both run out together.
- A single node. A tree of one node is its own only leaf.
- A long chain. A tree of 200 nodes in a line has one leaf, at the bottom.
Common mistakes
- Counting a node with one child as a leaf. A leaf has no children at all.
- Pushing the left child before the right, so the stack hands out leaves right to left.
- Comparing the sets of leaf values instead of the sequences, which ignores order and repeats.
How to talk through it
- 1Clarify. Does only the order of leaf values matter, not the shape? Can values repeat?
- 2Name the traversal. A left-first DFS meets leaves in left-to-right order.
- 3Give the simple version. Collect both lists and compare; O(n) time and space.
- 4Improve it. Pull one leaf at a time from each tree with a stack, so a mismatch stops the walk early.
- 5Test out loud. Run swapped leaves, a prefix sequence, and two single nodes.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?