Magicsheet logo

Leaf-Similar Trees

Easy
39.6%
Updated 6/1/2025

Leaf-Similar Trees

What is this problem about?

The "Leaf-Similar Trees interview question" asks you to determine if two given binary trees have the same leaf sequence. A leaf is a node with no children. The leaf sequence is formed by collecting all leaf values in a left-to-right order. Even if the internal structures of the two trees are different, they are considered leaf-similar if their leaves, when read from left to right, form the same list. This "Leaf-Similar Trees coding problem" is a classic exercise in tree traversal and comparison.

Why is this asked in interviews?

This problem is popular in interviews at companies like Google and Microsoft because it tests a candidate's understanding of "Depth-First Search interview pattern" and tree data structures. It requires you to navigate the tree to find specific nodes (leaves) and maintain their relative order. It also tests your ability to choose the right data structure (like a list or a vector) to store and compare the leaf sequences efficiently.

Algorithmic pattern used

The core algorithmic pattern is Depth-First Search (DFS). By performing a pre-order or in-order traversal, you can ensure that you visit the leaves in the required left-to-right sequence. For each tree, you traverse down to the leaves, add their values to a collection, and then compare the two collections for equality.

Example explanation

Suppose we have two trees: Tree A: Root(1) -> Left(2), Right(3). Leaves are [2, 3]. Tree B: Root(5) -> Left(Root(6) -> Left(2)), Right(3). Leaves are [2, 3]. In Tree A, we visit the left child '2' (leaf) and then the right child '3' (leaf). Sequence: [2, 3]. In Tree B, we visit the left subtree's leaf '2' and then the right child '3' (leaf). Sequence: [2, 3]. Since both sequences are identical, these trees are leaf-similar.

Common mistakes candidates make

  • Incorrect leaf identification: Forgetting that a leaf MUST have both left and right children as null.
  • Traversal order errors: Using Breadth-First Search (BFS), which might not preserve the left-to-right leaf order correctly depending on the tree's depth.
  • Memory inefficiency: Storing the entire tree instead of just the leaf values.

Interview preparation tip

Mastering DFS is essential for tree-based problems. Practice writing both recursive and iterative versions of DFS. For this problem, focus on how to stop the traversal at the leaves and collect their values in a way that allows for an easy comparison at the end.

Similar Questions