Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Home
Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
▲455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
DSA Corner
DashboardQuestionsTopicsCompaniesSheets

Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
▲455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
DSA Corner
DashboardQuestionsTopicsCompaniesSheets
Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
▲455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
DSA Corner
DashboardQuestionsTopicsCompaniesSheets
Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
▲455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
DSA Corner
DashboardQuestionsTopicsCompaniesSheets
Back to Problems

872. Leaf-Similar Trees

Easy70.0% Acceptance
TreeDepth-First SearchBinary Tree
Asked by:
G
Google
ProblemSolutions (4)VideosCompanies (1)Notes

Problem Statement

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].
Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
▲455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions

Approach

The key idea in Leaf-Similar Trees is to compare the sequence of leaf nodes from two binary trees. A leaf node is defined as a node with no left or right child. The problem becomes easier if we think of it as generating the leaf value sequence for each tree and then checking whether the two sequences are identical.

A common strategy is to use Depth-First Search (DFS). Traverse each tree recursively and collect values only when a node has node.left == null and node.right == null. Store these values in an ordered structure such as a list. Since DFS naturally explores the entire tree, it ensures every leaf is visited in left-to-right order.

After generating both sequences, simply compare them. If they match exactly, the trees are leaf-similar. The traversal touches each node once, giving a time complexity of O(n + m), where n and m are the sizes of the two trees. The extra space used mainly comes from recursion and storing leaf sequences.

Complexity

ApproachTime ComplexitySpace Complexity
DFS traversal to collect leaf sequences and compareO(n + m)O(n + m)

Video Solution Available

NeetCodeIO

View all video solutions

Solutions (4)

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.

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.

PythonC++
1class TreeNode:
2    def __init__(self, val=0, left=None, right=None):
3        self.val = val
4        self.left = left
5        self.right = right
6
7class Solution:
8    def leafSimilar(self, root1: TreeNode, root2: TreeNode) -> bool:
9        def dfs(node):
10            if not node:
11                return []
12            if not node.left and not node.right:
13                return [node.val]
14            return dfs(node.left) + dfs(node.right)
15
16        return dfs(root1) == dfs(root2)

Explanation

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.

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.

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.

JavaJavaScript
1import java.util.Stack;
2


Video Solutions

Watch expert explanations and walkthroughs

Leaf-Similar Trees - Leetcode 872 - Python

NeetCodeIO
7:0417,972 views

Asked By Companies

1 companies
G
Google

Prepare for Interviews

Practice problems asked by these companies to ace your technical interviews.

Explore More Problems

Notes

Personal Notes

Jot down your thoughts, approach, and key learnings

0 characters

Similar Problems

Binary Tree Inorder TraversalEasy
Validate Binary Search TreeMedium
Recover Binary Search TreeMedium
Same TreeEasy
More similar problems

Related Topics

TreeDepth-First SearchBinary Tree

Problem Stats

Acceptance Rate70.0%
DifficultyEasy
Companies1

Practice on LeetCode

Solve with full IDE support and test cases

Solve Now

Frequently Asked Questions

Why does DFS work well for Leaf-Similar Trees?

DFS explores each branch fully before moving to the next, making it easy to detect leaf nodes during traversal. By recording leaf values when both children are null, we can naturally build the leaf sequence in the correct order.

Is Leaf-Similar Trees asked in FAANG interviews?

Yes, variations of binary tree traversal problems are common in FAANG-style interviews. While this specific problem is labeled easy, it tests understanding of DFS, recursion, and tree traversal patterns that frequently appear in technical interviews.

What is the optimal approach for Leaf-Similar Trees?

The optimal approach uses Depth-First Search (DFS) to collect the leaf node values from both trees in left-to-right order. After generating these sequences, compare them directly. If the sequences match, the trees are considered leaf-similar.

What data structure is best for solving Leaf-Similar Trees?

A simple list or array works well to store the leaf values encountered during DFS traversal. The order of insertion matters because the problem requires comparing the exact sequence of leaves between two trees.

3
class
TreeNode
{
4
int
val
;
5
TreeNode
left
;
6
TreeNode
right
;
7
TreeNode
(
int
x
)
{
val
=
x
;
}
8
}
9
10
class
Solution
{
11
public
boolean
leafSimilar
(
TreeNode
root1
,
TreeNode
root2
)
{
12
return
getLeafSequence
(
root1
)
.
equals
(
getLeafSequence
(
root2
)
)
;
13
}
14
15
private
Stack
<
Integer
>
getLeafSequence
(
TreeNode
root
)
{
16
Stack
<
TreeNode
>
stack
=
new
Stack
<
>
(
)
;
17
Stack
<
Integer
>
leaves
=
new
Stack
<
>
(
)
;
18
if
(
root
!=
null
)
stack
.
push
(
root
)
;
19
while
(
!
stack
.
isEmpty
(
)
)
{
20
TreeNode
node
=
stack
.
pop
(
)
;
21
if
(
node
.
left
==
null
&&
node
.
right
==
null
)
{
22
leaves
.
push
(
node
.
val
)
;
23
}
24
if
(
node
.
right
!=
null
)
stack
.
push
(
node
.
right
)
;
25
if
(
node
.
left
!=
null
)
stack
.
push
(
node
.
left
)
;
26
}
27
return
leaves
;
28
}
29
}

Explanation

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.