Browse curriculum

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.

  1. DFS the first tree. At each node, if it has no children it is a leaf: append its value. Then recurse left, then right.
  2. DFS the second tree the same way into a second list.
  3. 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

Free preview: the first 8 of 26 steps

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 == second
Leaf-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, 3 and 3, 2 are 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

The approach, step by step

  1. Collect tree 1’s leaves

    DFS from the root, left child before right, appending every node that has no children.

  2. Collect tree 2’s leaves

    Run the same DFS on the second tree.

  3. Compare

    The trees are leaf-similar exactly when the two lists are equal.

Frequently asked questions

Why does a DFS find the leaves in left-to-right order?

Preorder, inorder and postorder all finish a node’s whole left subtree before its right subtree, so any leaf on the left is reached before any leaf on the right. That is exactly the left-to-right leaf order the problem asks for. Visiting the right child first would give the sequence reversed.


Do the trees need the same shape?

No. Only the leaf sequence is compared, so trees with different shapes, depths and internal values can still be leaf-similar. LeetCode example 1 is two different trees that both have leaves 6, 7, 4, 9, 8.


Can it be done without storing both lists?

Yes: run an iterative DFS on each tree with its own stack and pull one leaf at a time from each, stopping at the first difference. That keeps O(h1 + h2) memory and can stop early, at the cost of more code. Collecting two lists is the usual interview answer.

New to the technique behind this problem? Watch it run step by step:

Depth First Search Visualization

Applying for software engineering roles? Free, no sign-up:

AI resume checker: match your resume to the job description