Leaf-Similar Trees (LeetCode 872): Solution and Explanation

Easy
Tree
Depth First Search
Binary Tree

You get the roots of two binary trees. Read each tree's leaves from left to right; return true if the two sequences are the same and false otherwise.

Intuition

The shapes of the trees do not matter at all. Only the leaves count, and only in the order they appear from left to right.

A depth-first search that always explores the left child before the right child reaches the leaves in that left-to-right order. Every leaf to the left of another lives in a subtree that the search finishes first.

So the plan is to turn each tree into a plain list of leaf values, then compare two lists. A node is a leaf exactly when it has no left child and no right child.

Approach: Iterative DFS to collect leaves, then compare

  1. Write a helper that walks a tree with a stack, starting from the root.
  2. Pop a node. If it has no children, append its value to the sequence.
  3. Push the right child first and the left child second, so the left child is popped next.
  4. Run the helper on both trees and return whether the two sequences are equal.

Step-by-step example

root1 = [3,5,1,6,2,9,8,null,null,7,4], root2 = [3,5,1,6,7,4,2,null,null,null,null,null,null,9,8]
  1. Tree 1: pop 3, push 1 and 5. Pop 5, push 2 and 6. Pop 6, a leaf: [6]. Pop 2, push 4 and 7. Pop 7 and 4, both leaves: [6,7,4]. Pop 1, push 8 and 9. Pop 9 and 8: [6,7,4,9,8].
  2. Tree 2: the shape is different, but the left-first walk meets 6, 7, 4, 9, 8 in that order: [6,7,4,9,8].
  3. Compare slot by slot: all five leaves match and the lengths are equal. Return true.

Code: Python, Java, C++

1class Solution:
2    def leafSimilar(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool:
3        def leaves(root):
4            seq = []
5            stack = [root]
6            while stack:
7                node = stack.pop()
8                if not node.left and not node.right:
9                    seq.append(node.val)
10                if node.right:
11                    stack.append(node.right)
12                if node.left:
13                    stack.append(node.left)
14            return seq
15        return leaves(root1) == leaves(root2)
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n1 + n2)

Each node of each tree is pushed and popped once, and the final comparison is linear in the number of leaves.

Space

O(n1 + n2)

The leaf lists can hold about half of each tree's nodes, and the stack holds up to the tree height plus pending siblings.

Other approaches

Recursive DFS (time O(n1 + n2), space O(h1 + h2))

The same left-first traversal written recursively: visit left, visit right, and record the node if it has no children. Shorter, and fine here because trees have at most 200 nodes.

Lazy leaf generators (time O(n1 + n2), space O(h1 + h2))

Produce leaves one at a time from each tree with two stacks or generators and compare as you go. It stops at the first mismatch and never stores the full sequences.

Common mistakes

  • Pushing the left child before the right child onto a stack. The stack is last in, first out, so that pops the right side first and reverses the leaf order.
  • Treating a node with one child as a leaf. A leaf needs both children missing.
  • Comparing only the multiset of leaves. [1,2,3] and [1,3,2] have the same leaf values but in a different order, so the answer is false.
  • Forgetting to compare lengths when you compare element by element: one sequence can be a prefix of the other.

Frequently asked questions

Why does a left-first DFS read leaves left to right?

For any two leaves, there is a lowest node where their paths split. The leaf on the left lives in that node's left subtree, which the search finishes completely before it enters the right subtree.

Can I use BFS instead?

Not directly. BFS visits leaves by depth, so a shallow leaf on the right would come before a deep leaf on the left. You would have to sort by horizontal order afterward, which DFS gives for free.

Do the trees need the same number of nodes?

No. Only the leaves are compared, so trees of very different shapes and sizes can be leaf-similar.

Can the comparison stop early?

Yes, with lazy generators you can stop at the first mismatch. Collecting both lists first is simpler and has the same worst case.