Talentd
FleetCode
Make and follow sheets.Sign in

Leaf-Similar Trees solution and explanation

EasyBinary TreeDepth-First SearchTree6 min read70.0% acceptanceUpdated 9 Apr 2026
Leaf-Similar Trees - Leetcode 872 - PythonNeetCodeIO · 7:04 · 20K viewsWatch on YouTube
9 more videos on this problem
  1. Leaf-Similar Trees - Leetcode 872 - PythonNeetCodeIO · 7:04 · 20K views
  2. Leaf Similiar Trees - LeetCode Problem #872algoviz-xyz · 6:51 · 2K views
  3. Leaf Similar Trees - LeetCode 872 - Python #leetcode #leetcode75Deepti Talesra · 9:00 · 2K views
  4. 872. Leaf-Similar Trees | 2 Ways | Better - Optimal | TreesAryan Mittal · 15:20 · 2K views
  5. Leetcode | 872. Leaf-Similar Trees | Easy | Java SolutionDeveloper Docs · 6:21 · 1K views
  6. Leeetcode 872 Leaf-Similar Trees | Coding Decoded SDE SheetCoding Decoded · 6:16 · 923 views
  7. 872. Leaf-Similar Trees || LeetCode || Code Solution || Binary treecode Explainer · 3:26 · 740 views
  8. 872. Leaf-Similar Trees | JavaScript | DFS | LeetCode Daily Challenge | Easy Solution & ExplanationLeetCodeWithMonu · 10:03 · 533 views
  9. Leaf-Similar Trees | Leetcode 872 | Amazon Google Facebook interview questionSuper Lazy Coder · 6:57 · 177 views
  10. Solving the '872. Leaf-Similar Trees' Problem in Java LeetCode 75 Study PlanCoding with Christian · 10:28 · 173 views

The problem

Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a leaf value sequence.

For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8).

Two binary trees are considered leaf-similar if their leaf value sequence is the same.

Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar.

Example 1:

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]
Output: true

Example 2:

Input: root1 = [1,2,3], root2 = [1,3,2]
Output: false

Constraints:

  • The number of nodes in each tree will be in the range [1, 200].
  • Both of the given trees will have values in the range [0, 200].

Approach overview

Problem Overview: Two binary trees are leaf-similar if the sequence of values from their leaf nodes (left to right) is identical. Traverse both trees, collect their leaf sequences, then compare the results. If the sequences match exactly, the trees are leaf-similar.

The key observation: only leaf nodes matter. Internal nodes and structure differences are irrelevant as long as the final leaf order is the same.

Approach 1: Recursive Depth-First Search (DFS) to Extract Leaf Sequences (Time: O(n + m), Space: O(h1 + h2))

Use a recursive depth-first search to traverse each tree and collect leaf values into an array. During traversal, check if the current node has no left and right children. If so, append its value to the sequence. Recursion naturally visits nodes in left-to-right order, which preserves the correct leaf ordering. After building both arrays, compare them element by element. Traversing each node once gives O(n + m) time where n and m are node counts of the two trees. Space complexity is O(h1 + h2) from recursion stacks, where h is the tree height.

This approach is clean and easy to reason about. Most interviewers expect this solution because it directly leverages recursion for tree traversal.

Approach 2: Iterative Depth-First Search (DFS) Using Stack (Time: O(n + m), Space: O(n + m))

An iterative DFS replaces recursion with an explicit stack. Push the root node onto the stack, repeatedly pop nodes, and push their children. When a node with no children is encountered, record its value in the leaf sequence. This approach simulates the traversal performed in recursive DFS but avoids recursion depth limits. After generating the sequences for both trees, compare them to determine if the trees are leaf-similar.

Iterative traversal is useful in environments where recursion depth might overflow or when you prefer explicit control over traversal order. The stack may temporarily hold many nodes, leading to O(n + m) auxiliary space in the worst case.

Both methods rely on standard tree traversal and operate directly on a binary tree. The only real task is correctly identifying leaf nodes and preserving their order.

Recommended for interviews: Recursive DFS is typically expected because it is concise and clearly expresses the traversal logic. Showing the recursive approach demonstrates comfort with tree recursion. The iterative stack version is still valuable if you want to avoid recursion or show deeper control over DFS mechanics.

Approach 1: Approach 1: Recursive Depth-First Search (DFS) to Extract Leaf Sequences

This approach involves using a recursive depth-first search (DFS) to traverse each binary tree and collect the leaf node values by diving into each sub-tree starting from the root node. We store the values of all leaf nodes from left to right in a list. After extracting the sequences from both trees, we compare these sequences to determine if the trees are leaf-similar.

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def leafSimilar(self, root1: TreeNode, root2: TreeNode) -> bool:
        def dfs(node):
            if not node:
                return []
            if not node.left and not node.right:
                return [node.val]
            return dfs(node.left) + dfs(node.right)

        return dfs(root1) == dfs(root2)
#include <vector>
using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};

class Solution {
public:
    bool leafSimilar(TreeNode* root1, TreeNode* root2) {
        vector<int> leaves1, leaves2;
        dfs(root1, leaves1);
        dfs(root2, leaves2);
        return leaves1 == leaves2;
    }

private:
    void dfs(TreeNode* node, vector<int>& leaves) {
        if (!node) return;
        if (!node->left && !node->right) {
            leaves.push_back(node->val);
        } else {
            dfs(node->left, leaves);
            dfs(node->right, leaves);
        }
    }
};

We define a nested function dfs inside our main function to recursively traverse the binary tree. The dfs function returns a list of leaf node values by first checking if a node is null (in which case it returns an empty list), then it checks if the node is a leaf node (no left and right children), and if so, it returns a list containing the node's value. Otherwise, it recursively calls itself on the left and right children and concatenates their results. Lastly, we compare the two leaf sequences to decide if the trees are leaf-similar.

Complexity

Time Complexity: O(N) where N is the number of nodes in the tree, as we need to visit each node.
Space Complexity: O(H) where H is the height of the tree, due to the recursive stack.

Try this approach in the editor

Approach 2: Approach 2: Iterative Depth-First Search (DFS) Using Stack

This method employs an iterative version of depth-first search utilizing a stack to collect leaves of the tree. By substituting recursion with a stack, we manually handle tree traversal, but the core logic remains similar: traverse each tree, collect leaves, and compare leaf sequences.

import java.util.Stack;

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}

class Solution {
    public boolean leafSimilar(TreeNode root1, TreeNode root2) {
        return getLeafSequence(root1).equals(getLeafSequence(root2));
    }

    private Stack<Integer> getLeafSequence(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        Stack<Integer> leaves = new Stack<>();
        if (root != null) stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();
            if (node.left == null && node.right == null) {
                leaves.push(node.val);
            }
            if (node.right != null) stack.push(node.right);
            if (node.left != null) stack.push(node.left);
        }
        return leaves;
    }
}
function TreeNode(val, left, right) {
    this.val = val === undefined ? 0 : val;
    this.left = left === undefined ? null : left;
    this.right = right === undefined ? null : right;
}

function leafSimilar(root1, root2) {
    function getLeafSequence(root) {
        const stack = [], leaves = [];
        if (root !== null) stack.push(root);
        while (stack.length) {
            const node = stack.pop();
            if (!node.left && !node.right) leaves.push(node.val);
            if (node.right) stack.push(node.right);
            if (node.left) stack.push(node.left);
        }
        return leaves;
    }
    return JSON.stringify(getLeafSequence(root1)) === JSON.stringify(getLeafSequence(root2));
}

Here, a Stack is used for both implementing the DFS traversal and collecting leaf node values iteratively. For leaf nodes, their values are added to a separate stack (list) leaves. By performing this for both root1 and root2, we get their leaf sequences, which are compared for equality at the end.

Complexity

Time Complexity: O(N), with N as the number of nodes in the tree, because every node is visited.
Space Complexity: O(H), where H is the height of the tree. This space is used by the stack during DFS traversal.

Try this approach in the editor

Approach 3: DFS

We can use Depth-First Search (DFS) to traverse the leaf nodes of the two trees, storing the values of the leaf nodes in two lists l_1 and l_2 respectively. Finally, we compare whether the two lists are equal.

Time complexity is O(n), and space complexity is O(n). Here, n is the number of nodes in the tree.

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func leafSimilar(root1 *TreeNode, root2 *TreeNode) bool {
	l1, l2 := []int{}, []int{}
	var dfs func(*TreeNode, *[]int)
	dfs = func(root *TreeNode, nums *[]int) {
		if root.Left == root.Right {
			*nums = append(*nums, root.Val)
			return
		}
		if root.Left != nil {
			dfs(root.Left, nums)
		}
		if root.Right != nil {
			dfs(root.Right, nums)
		}
	}
	dfs(root1, &l1)
	dfs(root2, &l2)
	return reflect.DeepEqual(l1, l2)
}
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
//   pub val: i32,
//   pub left: Option<Rc<RefCell<TreeNode>>>,
//   pub right: Option<Rc<RefCell<TreeNode>>>,
// }
//
// impl TreeNode {
//   #[inline]
//   pub fn new(val: i32) -> Self {
//     TreeNode {
//       val,
//       left: None,
//       right: None
//     }
//   }
// }
use std::cell::RefCell;
use std::rc::Rc;
impl Solution {
    pub fn leaf_similar(
        root1: Option<Rc<RefCell<TreeNode>>>,
        root2: Option<Rc<RefCell<TreeNode>>>,
    ) -> bool {
        let mut l1 = Vec::new();
        let mut l2 = Vec::new();
        Self::dfs(&root1, &mut l1);
        Self::dfs(&root2, &mut l2);
        l1 == l2
    }

    fn dfs(node: &Option<Rc<RefCell<TreeNode>>>, nums: &mut Vec<i32>) {
        if let Some(n) = node {
            let n = n.borrow();
            if n.left.is_none() && n.right.is_none() {
                nums.push(n.val);
                return;
            }
            if n.left.is_some() {
                Self::dfs(&n.left, nums);
            }
            if n.right.is_some() {
                Self::dfs(&n.right, nums);
            }
        }
    }
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Approach 1: Recursive Depth-First Search (DFS) to Extract Leaf Sequences

Time Complexity: O(N) where N is the number of nodes in the tree, as we need to visit each node.
Space Complexity: O(H) where H is the height of the tree, due to the recursive stack.

Approach 2: Iterative Depth-First Search (DFS) Using Stack

Time Complexity: O(N), with N as the number of nodes in the tree, because every node is visited.
Space Complexity: O(H), where H is the height of the tree. This space is used by the stack during DFS traversal.

DFS–

Complexity analysis

ApproachTimeSpaceWhen to Use
Recursive DFS to Collect Leaf SequencesO(n + m)O(h1 + h2)Best general solution; simple recursion and minimal extra storage
Iterative DFS Using StackO(n + m)O(n + m)When recursion depth is a concern or iterative traversal is preferred

Frequently asked questions

Is Leaf-Similar Trees easy or hard?

Leaf-Similar Trees is categorized as an Easy problem. The main requirement is recognizing leaf nodes and performing a simple DFS traversal while preserving left-to-right ordering.

Leaf-Similar Trees Python/Java solution

Python and Java solutions both implement DFS traversal. Python often uses recursion to append leaf values to a list, while Java may use either recursion or an explicit stack for iterative DFS. Both approaches run in O(n + m) time.

How to solve Leaf-Similar Trees in O(n)?

Run DFS on each tree to extract leaf nodes in left-to-right order. Store the leaf values in arrays and compare the arrays at the end. Since every node is processed once, the total runtime remains linear in the number of nodes.

What is the best approach for Leaf-Similar Trees?

Recursive depth-first search (DFS) is the most common approach. Traverse each tree, record values of nodes that have no children, and compare the two leaf sequences. The traversal visits each node once, giving O(n + m) time complexity.

Is Leaf-Similar Trees asked at Google/Amazon/Meta?

Leaf-Similar Trees represents a typical easy-level binary tree traversal question. Variants of leaf traversal and DFS-based comparisons appear in interviews at companies like Amazon and Google to test tree fundamentals and recursion.

What data structure is used in Leaf-Similar Trees?

The problem uses a binary tree as the core data structure. Depth-first search is used to traverse the tree, and either recursion stacks or an explicit stack structure helps maintain traversal state while collecting leaf nodes.

What is the time complexity of Leaf-Similar Trees?

The time complexity is O(n + m), where n and m are the number of nodes in the two binary trees. Each node is visited exactly once during DFS traversal. Comparing the two leaf sequences takes linear time relative to the number of leaves.

Comments

Now write it yourselfClose this page and solve Leaf-Similar Trees in the editor, without looking.
Practise Leaf-Similar Trees