← Back to DSA
#100
Same Tree
Same Tree solution for LeetCode 100, with the key idea, complexity breakdown, and working code in Java, C++, JavaScript, TypeScript, C, Go, and Rust.
Solve on LeetCode ↗Same Tree
Why it belongs on this sheet
This is a clean structural recursion problem and good practice for comparing two traversals in lockstep.
Pattern
Parallel DFS
Approach
Two trees are the same only if both current nodes are null, or both exist with equal values and matching left and right subtrees.
Java solution
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null || q == null) {
return p == q;
}
return p.val == q.val
&& isSameTree(p.left, q.left)
&& isSameTree(p.right, q.right);
}
}
Complexity
- Time:
O(n) - Space:
O(h)
Interview note
A strong verbal model is: "compare node, compare left, compare right."
Dynamic Programming
7 DP Patterns > 100 LeetCode Questions
Most DP questions are repeated ideas. Stop treating DP like chaos. Learn the 7 repeatable patterns that unlock most placement-level questions.
7 patternsProgress tracking
Read 7 patterns (5 min)