NeetCode #390LC-100EasyTreesBlind 75NC 150NC 250
← Back to All Problems#390 · #100 · Same Tree(相同的树)
📌 Problem Statement & Constraints
Given the roots of two binary trees
p and q, return true if they are structurally identical and every corresponding node has the same value. Constraints: the number of nodes in each tree is in [0, 100].💡 Core Algorithmic Approaches
- Compare the roots recursively: both
Nonemeans equal, exactly oneNonemeans unequal. - If both exist, the values must match and both subtrees must match.
- The base cases must be checked in the order
both Nonetheneither None, otherwise aNonewould be dereferenced. - The recursion visits at most the smaller tree in full.
💻 Benchmark Python3 Implementation
class Solution:
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
if not p and not q:
return True # both empty -> equal
if not p or not q:
return False # exactly one empty -> unequal
return (p.val == q.val
and self.isSameTree(p.left, q.left)
and self.isSameTree(p.right, q.right))⚡ Complexity Deep Dive
⏱️ Time Complexity
O(min(m, n)): the recursion stops as soon as a mismatch is found.
💾 Space Complexity
O(h) for the recursion stack.
⚠️ Interview Pitfalls & Follow-ups
- Checking
p.val == q.valbefore theNonecases: aNonewould raise anAttributeError. - Using
p.val == q.valalone: the structure would not be verified, so a node with an extra child would pass. - Comparing only the left subtrees: both sides must be checked.
- Assuming the trees have equal size: they may differ, which the
either Nonecase catches.