LeetCode ยท #100
Same Tree Solution
Given two binary trees, check if they are structurally identical and have the same node values.
01
Section One ยท Problem
Problem Statement
Given the roots of two binary trees p and q, write a function to check if they are the same or not. Two trees are the same if they are structurally identical and the nodes have the same values.
Example
Input: p = [1,2,3], q = [1,2,3]
Output: true
Constraints
โข 0 โค number of nodes โค 100 โข -10โด โค Node.val โค 10โด
02
Section Two ยท Approach 1
Serialize & Compare โ O(n)
Serialize both trees to strings (preorder with null markers) and compare strings. Works but allocates O(n) string space unnecessarily.
03
Section Three ยท Approach 2
Recursive Comparison โ O(n)
Compare nodes in parallel: (1) both null โ true, (2) one null โ false, (3) values differ โ false, (4) recurse on left and right children.
๐ก Mental model: Two people walk through two houses simultaneously. At each room they check: "Same room exists? Same furniture?" If any mismatch, stop. If both reach dead ends at the same time โ identical layout.
๐ฏ Building block:
isSameTree is used as a helper in LC 572 (Subtree of Another Tree) โ check it at every node of the main tree.
04
Section Four ยท Trace
Visual Walkthrough
Parallel comparison โ p=[1,2,3] vs q=[1,2,3]
05
Section Five ยท Implementation
Code โ Java & Python
Java โ Recursive
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null && q == null) return true;
if (p == null || q == null) return false;
if (p.val != q.val) return false;
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
}
Python โ Recursive
class Solution:
def isSameTree(self, p, q) -> bool:
if not p and not q: return True if not p or not q: return False return (p.val == q.val
and self.isSameTree(p.left, q.left)
and self.isSameTree(p.right, q.right))
06
Section Six ยท Analysis
Complexity Analysis
| Approach | Time | Space |
|---|---|---|
| Recursive | O(n) | O(h) โ stack depth |
07
Section Seven ยท Edge Cases
Edge Cases & Pitfalls
| Case | Input | Why It Matters |
|---|---|---|
| Both empty | null, null | Same โ true. |
| One empty | [1], null | Different structure โ false. |
| Same structure, different values | [1,2], [1,3] | Values mismatch at p.left vs q.left โ false. |