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);
}
};
Difficulty
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
AI Disclaimer
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.
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:
- When both pointers are null, the function concludes that the corresponding subtrees are empty and therefore identical, returning
true.
if (!p && !q)
return true;
- 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
pandqare null, triggering the first base case and yieldingtrue. - 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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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++ |
Videos
Solved On The Same Day
- problem 1: Two Sum
- problem 9: Palindrome Number
- problem 14: Longest Common Prefix
- problem 20: Valid Parentheses
- problem 26: Remove Duplicates from Sorted Array
- problem 27: Remove Element
- problem 83: Remove Duplicates from Sorted List
- problem 88: Merge Sorted Array
- problem 94: Binary Tree Inorder Traversal
- problem 104: Maximum Depth of Binary Tree
- problem 121: Best Time to Buy and Sell Stock
- problem 136: Single Number
- problem 141: Linked List Cycle
- problem 169: Majority Element
- problem 190: Reverse Bits
- problem 226: Invert Binary Tree
- problem 234: Palindrome Linked List
- problem 1114: Print in Order
- problem 3: Longest Substring Without Repeating Characters
- problem 7: Reverse Integer
- problem 8: String to Integer (atoi)
- problem 11: Container With Most Water
- problem 12: Integer to Roman
- problem 15: 3Sum
- problem 17: Letter Combinations of a Phone Number
- problem 22: Generate Parentheses
- problem 31: Next Permutation
- problem 36: Valid Sudoku
- problem 39: Combination Sum
- problem 40: Combination Sum II
- problem 45: Jump Game II
- problem 46: Permutations
- problem 47: Permutations II
- problem 48: Rotate Image
- problem 49: Group Anagrams
- problem 55: Jump Game
- problem 59: Spiral Matrix II
- problem 75: Sort Colors
- problem 77: Combinations
- problem 91: Decode Ways
- problem 95: Unique Binary Search Trees II
- problem 96: Unique Binary Search Trees
- problem 134: Gas Station
- problem 164: Maximum Gap
- problem 189: Rotate Array
- problem 215: Kth Largest Element in an Array
- problem 238: Product of Array Except Self
- problem 287: Find the Duplicate Number
- problem 322: Coin Change
- problem 347: Top K Frequent Elements
- problem 377: Combination Sum IV
- problem 438: Find All Anagrams in a String
- problem 474: Ones and Zeroes
- problem 518: Coin Change II
- problem 526: Beautiful Arrangement
- problem 763: Partition Labels
- problem 983: Minimum Cost For Tickets
- problem 994: Rotting Oranges
- problem 1027: Longest Arithmetic Subsequence
- problem 2140: Solving Questions With Brainpower
- problem 2466: Count Ways To Build Good Strings
- problem 4: Median of Two Sorted Arrays
- problem 41: First Missing Positive
Extra
- 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