Same Tree Problem
Description
LeetCode Problem 100.
Given the roots of two binary trees p and q, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.
Example 1:
Input: p = [1,2,3], q = [1,2,3]
Output: true
Example 2:
Input: p = [1,2], q = [1,null,2]
Output: false
Example 3:
Input: p = [1,2,1], q = [1,1,2]
Output: false
Constraints:
- The number of nodes in both trees is in the range [0, 100].
- -10^4 <= Node.val <= 10^4
Solution
Approach: Recursive Comparison
Two trees are the same exactly when their roots match and their left subtrees are the same and their right subtrees are the same. That definition translates directly into recursion on the pair (p, q):
- If both
pandqare null, they are the same (two empty trees). - If only one of them is null, they differ: one tree has a node where the other has none.
- If both exist but
p.val != q.val, they differ. - Otherwise compare
p.leftwithq.leftandp.rightwithq.right; both must be the same.
The order of the null checks matters. Check "both null" first, then "either null", and only then read .val, so we never read a value from a missing node.
Comparing only the traversal order of values is not enough. In Example 2, [1,2] and [1,null,2] contain the same values, but 2 is a left child in one tree and a right child in the other. The recursion catches this because it compares the children position by position.
&& stops at the first difference, so the comparison ends early when the trees differ near the top.
Complexity: O(n) time and O(h) extra space for the recursion, where n is the number of nodes in the smaller tree and h is its height.
class Solution:
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
if p is None and q is None:
return True # both empty
if p is None or q is None:
return False # only one is empty
if p.val != q.val:
return False
return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
Now write it from memory
Close the write-up and solve it yourself against the tests.