Home
DSA Patterns
Depth-First Search
Leaf-Similar Trees
Leaf-Similar Trees (LeetCode 872)
Leaf-Similar Trees (LeetCode 872): two binary trees are leaf-similar when their leaves, read left to right, form the same sequence. Collect each tree’s leaves with a DFS and compare the two lists.
Problem Understanding
Leaf-Similar Trees (LeetCode 872): read a binary tree’s leaves from left to right to get its leaf value sequence. Two trees are leaf-similar if their leaf value sequences are the same. Given the roots of two trees, return true if they are leaf-similar.
Examples: [3,5,1,6,2,9,8,null,null,7,4] and [3,5,1,6,7,4,2,null,null,null,null,null,null,9,8] both have leaves 6, 7, 4, 9, 8 → true; [1,2,3] and [1,3,2] have leaves 2, 3 and 3, 2 → false.
The Intuition: Read the Leaves Off Each Tree
The shapes do not matter, only the order the leaves come in. A depth-first search that always goes left before right meets the leaves in exactly that order.
- DFS the first tree. At each node, if it has no children it is a leaf: append its value. Then recurse left, then right.
- DFS the second tree the same way into a second list.
- Compare the lists. Equal lists mean leaf-similar.
This is the DFS on trees pattern with a list carried through the recursion. Same Tree compares two trees node by node; here only the leaves are compared, so different shapes can still match.
Leaf-Similar Trees Visualization
GREEN = LEAF COLLECTED · OUTLINED = CALL STACK
WALK TREE 1
tree 1
position
:
Answer
:
leaves of tree 1
None yet
leaves of tree 2
None yet
Walk tree 1 from root 3, left child before right, collecting leaves
Next
3 is not a leaf. Go left to 5, then right to 1
Tree 1
Tree 2
The figure walks tree 1, then tree 2. Leaves turn green as they are appended to their row below the tree, and the call stack’s path is outlined. Once both lists are built, the compare steps walk them side by side. Try Example 2, where the same leaves come in a different order, and Extra leaf, where one list is longer.
Leaf-Similar Trees Dry Run
Input: 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].
| Tree | Visit order | Leaves appended |
|---|---|---|
| 1 | 3, 5, 6, 2, 7, 4, 1, 9, 8 | 6, 7, 4, 9, 8 |
| 2 | 3, 5, 6, 7, 1, 4, 2, 9, 8 | 6, 7, 4, 9, 8 |
Positions 0 to 4 match (6, 7, 4, 9, 8).
Answer: true.
Leaf-Similar Trees LeetCode Solution
One helper collects a tree’s leaves; call it on both roots and compare the results.
Leaf-Similar Trees Code
1var leafSimilar = function(root1, root2) {2 const leaves = (node, out) => {3 if (node === null) {4 return out;5 }6 if (node.left === null && node.right === null) {7 out.push(node.val);8 }9 leaves(node.left, out);10 leaves(node.right, out);11 return out;12 };13 const first = leaves(root1, []);14 const second = leaves(root2, []);15 return first.length === second.length && first.every((v, i) => v === second[i]);16};
Leaf-Similar Trees in Python, Java, C++, TypeScript and C
Leaf-Similar Trees in Python
class Solution:
def leafSimilar(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool:
def leaves(node, out):
if node is None:
return out
if node.left is None and node.right is None:
out.append(node.val)
leaves(node.left, out)
leaves(node.right, out)
return out
first = leaves(root1, [])
second = leaves(root2, [])
return first == secondLeaf-Similar Trees in Java
class Solution {
public boolean leafSimilar(TreeNode root1, TreeNode root2) {
List<Integer> first = new ArrayList<>();
List<Integer> second = new ArrayList<>();
leaves(root1, first);
leaves(root2, second);
return first.equals(second);
}
private void leaves(TreeNode node, List<Integer> out) {
if (node == null) {
return;
}
if (node.left == null && node.right == null) {
out.add(node.val);
}
leaves(node.left, out);
leaves(node.right, out);
}
}Leaf-Similar Trees in C++
class Solution {
void leaves(TreeNode* node, vector<int>& out) {
if (node == nullptr) {
return;
}
if (node->left == nullptr && node->right == nullptr) {
out.push_back(node->val);
}
leaves(node->left, out);
leaves(node->right, out);
}
public:
bool leafSimilar(TreeNode* root1, TreeNode* root2) {
vector<int> first, second;
leaves(root1, first);
leaves(root2, second);
return first == second;
}
};Leaf-Similar Trees in TypeScript
function leafSimilar(root1: TreeNode | null, root2: TreeNode | null): boolean {
const leaves = (node: TreeNode | null, out: number[]): number[] => {
if (node === null) {
return out;
}
if (node.left === null && node.right === null) {
out.push(node.val);
}
leaves(node.left, out);
leaves(node.right, out);
return out;
};
const first = leaves(root1, []);
const second = leaves(root2, []);
return first.length === second.length && first.every((v, i) => v === second[i]);
}Leaf-Similar Trees in C
static void leaves(struct TreeNode* node, int* out, int* n) {
if (node == NULL) {
return;
}
if (node->left == NULL && node->right == NULL) {
out[(*n)++] = node->val;
}
leaves(node->left, out, n);
leaves(node->right, out, n);
}
bool leafSimilar(struct TreeNode* root1, struct TreeNode* root2) {
int first[200], second[200], m = 0, n = 0;
leaves(root1, first, &m);
leaves(root2, second, &n);
if (m != n) {
return false;
}
for (int i = 0; i < m; i++) {
if (first[i] != second[i]) {
return false;
}
}
return true;
}Edge Cases & Common Mistakes
- Visiting right before left: the sequence comes out reversed, and
[1,2,3]vs[1,2,3]would still pass, hiding the bug. - Comparing sets or sorted lists: order matters;
2, 3and3, 2are not leaf-similar. - A single-node tree: the root is a leaf, so its sequence is just its value.
- Different lengths: one tree may have more leaves; a list comparison handles it, a manual loop must check the lengths.
Summary
DFS each tree, left before right, appending every node with no children. The trees are leaf-similar when the two lists are equal. O(n + m) time, O(n + m) space for the lists and the recursion.
More practice: DSA interview questions with answers · patterns cheat sheet
