Problem 100

Abstract / Summary

Given two binary trees determine if they have the exact same structure and node values.

Note

The full problem description, including helpful examples, can be found on LeetCode.

C++ 0100.cpp

class Solution {
public:
    bool isSameTree(TreeNode* p, TreeNode* q) {
        if (!p && !q)
            return true;

        if (!p && q)
            return false;
        if (p && !q)
            return false;

        if (p->val != q->val)
            return false;

        return isSameTree(p->left, q->left) &&
               isSameTree(p->right, q->right);
    }
};
18 lines | 394 bytes | submitted August 8, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 68% (5+ million submissions).

Typical patterns to solve this problem:
  • Binary Tree
  • Breadth First Search
  • Depth First Search
  • Tree
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a class Solution with a single public member function isSameTree. The function determines whether two binary trees, rooted at pointers p and q, are structurally identical and contain the same node values. It follows a classic recursive depth-first strategy, comparing corresponding nodes in a synchronized walk of both trees.

Core Logic

At the heart of the algorithm is a recursive call that proceeds only when the current pair of nodes satisfies three conditions: both are non-null, their values match, and their respective left and right subtrees are also identical. The function returns a Boolean result that propagates up the call stack, ultimately reflecting the equivalence of the entire trees.

bool isSameTree(TreeNode* p, TreeNode* q) {
    // base cases and recursive checks are performed here
}

Recursive Traversal

The recursion mirrors a pre-order traversal: it first evaluates the current nodes, then recurses on the left children, and finally on the right children. This order ensures that any discrepancy is detected as early as possible, preventing unnecessary deeper exploration.

return isSameTree(p->left, q->left) &&
       isSameTree(p->right, q->right);

Base Cases

Three distinct base cases guard the recursion:

  1. When both pointers are null, the function concludes that the corresponding subtrees are empty and therefore identical, returning true.
if (!p && !q)
    return true;
  1. When one pointer is null while the other is not, the trees differ in structure at this position, leading to an immediate false.
if (!p && q)
    return false;
if (p && !q)
    return false;

These checks handle the asymmetry that can arise when one tree has a node where the other does not, preventing dereferencing of null pointers.

Value Comparison

If both nodes exist, their stored values are compared. A mismatch indicates that the trees cannot be the same, and the function returns false without further recursion.

if (p->val != q->val)
    return false;

Combination of Results

When the base cases and value comparison succeed, the function proceeds to evaluate the left and right subtrees. The logical AND operator ensures that both subtrees must be identical for the overall result to be true.

return isSameTree(p->left, q->left) &&
       isSameTree(p->right, q->right);

Edge Cases Handled

The implementation gracefully manages several edge conditions:

  • Completely empty trees: both p and q are null, triggering the first base case and yielding true.
  • Trees with differing depths: the asymmetrical null checks capture scenarios where one tree terminates earlier than the other.
  • Trees with identical structure but differing values: the explicit value comparison detects any value discrepancy at the exact node where it occurs.
  • Single-node trees: the algorithm correctly evaluates the root values and then encounters null children, satisfying the base case for both sides.

Performance Considerations

The recursive design inherently leverages the call stack to store traversal state, eliminating the need for auxiliary data structures such as explicit stacks or queues. By returning early on any mismatch-whether structural or value-based-the function avoids unnecessary exploration of the remaining subtree, which can lead to a reduction in total recursive calls for non-identical trees. This early exit behavior constitutes a practical optimization, especially for large, unbalanced trees where a difference may be found near the root.

The use of short-circuit evaluation in the final return statement (&&) further contributes to efficiency: if the left subtree comparison yields false, the right subtree is never examined, saving additional recursive invocations.

Overall, the code presents a concise and effective solution for tree equivalence checking, employing clear base case handling, direct value comparison, and a depth-first recursive pattern that naturally incorporates early termination for mismatched inputs.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have two big boxes filled with building blocks shaped like trees. Each tree has a center block with a number on it, and branches that might lead to more blocks on the left or the right.

To figure out if these two trees are exactly the same, you start at the very top. First, you check if both trees are empty at the same time. If they are both missing, they match. If one has a block and the other is empty, they definitely do not match.

Next, you look at the number on the block you are currently holding in each tree. If the numbers are different, you know right away the trees are not the same.

If the numbers match, you then peek at the branches. You check the left side of both trees to see if they look the same, and you do the same thing for the right side. You keep doing this over and over for every single branch until you have explored the whole tree. If every single block matches exactly, then both trees are identical.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 8.48 | σ = 0.74

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Rust JS Go PHP TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github AdelDaniel Dart
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++
bujosa Rust
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
Dijkstra-Edu Java
DimitrisJim C
everthis JS
fartem Ruby
fengvyi C++
gaosq0604 Python
Garvit244 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
Krazune C
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
muhammadfarhankt Go
pruthvikp Python
qiyuangong Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM Java
trung-hn Python
varunu28 Java
vthwang Java
XiaotaoGuo C++
yuanliu666 Kotlin
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, JavaScript, PHP, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
AdelDaniel Dart
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
bujosa Rust
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
Dijkstra-Edu Java
DimitrisJim C
everthis JavaScript
fartem Ruby
fengvyi C++
gaosq0604 Python
Garvit244 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
muhammadfarhankt Go
pruthvikp Python
qiyuangong Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM Java
trung-hn Python
varunu28 Java
vthwang Java
XiaotaoGuo C++
yuanliu666 Kotlin
YuriSpiridonov Python
zfang399 C++
63 links | 46 authors | 13 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Same Tree - Leetcode 100 - Python'
NeetCode 8 mins
Same Tree - Leetcode 100 - Python
YouTube video 'Same Tree (LeetCode 100) | Full solution with visuals and animations | Study Algorithms'
Nikhil Lohia 15 mins
Same Tree (LeetCode 100) | Full solution with visuals and animations | Study Algorithms
YouTube video 'Same Binary Tree - Leetcode 100 - Trees (Python)'
Greg Hogg 6 mins
Same Binary Tree - Leetcode 100 - Trees (Python)
YouTube video 'Same Tree | DFS | BFS | Google | Leetcode 100'
codestorywithMIK 15 mins
Same Tree | DFS | BFS | Google | Leetcode 100
YouTube video 'Same Tree | LeetCode 100 | C++, Java, Python'
Knowledge Center 22 mins
Same Tree | LeetCode 100 | C++, Java, Python
YouTube video 'Same Tree - LeetCode 100 - JavaScript'
AlgoJS 4 mins
Same Tree - LeetCode 100 - JavaScript
YouTube video 'Leetcode 100. Same Tree [Java]'
if else statement 6 mins
Leetcode 100. Same Tree [Java]
YouTube video 'Same Tree Leetcode Javascript | 100 Same Tree Leetcode'
Persistent Programmer 11 mins
Same Tree Leetcode Javascript | 100 Same Tree Leetcode
YouTube video 'LeetCode 100: The Same Tree - Interview Prep Ep 21'
Fisher Coder 11 mins
LeetCode 100: The Same Tree - Interview Prep Ep 21
YouTube video 'Same Tree - LeetCode 100 - Python #blind75 #leetcode'
Deepti Talesra 11 mins
Same Tree - LeetCode 100 - Python #blind75 #leetcode
YouTube video '100. Same Tree | JavaScript | Depth First Search | LeetCode Daily Challenge | Simple Explanation'
LeetCodeWithMonu 6 mins
100. Same Tree | JavaScript | Depth First Search | LeetCode Daily Challenge | Simple Explanation
YouTube video 'How To Solve "100  Same Tree" on LeetCode - JavaScript Easy'
Becoming A Better Dev (with David) 7 mins
How To Solve "100 Same Tree" on LeetCode - JavaScript Easy
YouTube video 'Same Tree | Recursive and Iterative | Leetcode - 100'
Algorithms Made Easy 5 mins
Same Tree | Recursive and Iterative | Leetcode - 100
YouTube video 'Leetcode | 100. Same Tree | Easy | Java Solution'
Developer Docs 7 mins
Leetcode | 100. Same Tree | Easy | Java Solution
YouTube video 'LeetCode 100: Same Tree'
Engineering Digest 4 mins
LeetCode 100: Same Tree
YouTube video 'Same Tree | Leet code 100 | Theory explained + Python code | July Leet code challenge'
Sai Anish Malla 6 mins
Same Tree | Leet code 100 | Theory explained + Python code | July Leet code challenge
YouTube video 'Same Tree - LeetCode 100 - Coding Interview Questions'
One Code Man 5 mins
Same Tree - LeetCode 100 - Coding Interview Questions
YouTube video '100. Same Tree Java Solution'
Code with Carter 5 mins
100. Same Tree Java Solution
YouTube video 'same tree | same tree leetcode | leetcode 100 | recursive | iterative'
Naresh Gupta 8 mins
same tree | same tree leetcode | leetcode 100 | recursive | iterative
YouTube video '100. Same Tree | February | Java | C++'
Mayur Programming Club 9 mins
100. Same Tree | February | Java | C++
20 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

18 easy 43 medium 2 hard
64 solutions   August 8, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality