Same Tree
Check whether two binary trees have the same shape and the same value in every position.
The problem
You get the roots of two binary trees, p and q. Return true if they are the same tree: identical shape, with equal values in matching positions. Otherwise return false.
Input p = [4, 7, 9, 1], q = [4, 7, 9, 1]
Output true
Both trees have 4 at the root, 7 and 9 below it, and 1 as the left child of 7.
Input p = [5, 3], q = [5, null, 3]
Output false
Both trees hold 5 and 3, but 3 is a left child in `p` and a right child in `q`.
How to spot the pattern
- You have to compare two trees position by position.
- Two trees are equal exactly when their roots match and both pairs of subtrees are equal.
The idea
Two trees are the same when their roots hold the same value, their left subtrees are the same and their right subtrees are the same. That definition is already a recursive function. The base cases take care of shape: two empty trees match, while an empty tree never matches a non-empty one.
Brute force: Serialize both trees with a marker for every missing child and compare the two strings, which is also O(n) time but builds O(n) extra text.
Step by step
- 1If both nodes are null, return
true. - 2If only one of them is null, or their values differ, return
false. - 3Otherwise return whether the two left children match and the two right children match.
See the pattern move
The tree dfs and bst pattern on a small example. Step through it, or press play.
Code
class Solution:
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
if p is None and q is None:
return True
if p is None or q is None or p.val != q.val:
return False
return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)Complexity
Time
O(n)
Space
O(h)
Each pair of nodes is compared at most once and the first mismatch ends the walk; the stack holds one call per level of the shorter tree.
Watch out for
- Comparing only the values in one traversal order:
[2, 1, 3]and the chain[1, null, 2, null, 3]have the same in-order values but different shapes. - Reading
p.valbefore checking thatpis not null.
Follow-up questions
How would you check whether one tree appears inside another as a subtree?
Run this same-tree check from every node of the bigger tree, which is O(m * n). Serializing both trees with null markers and searching for one string in the other gets it down to linear time.
Can you do it without recursion?
Keep a stack of node pairs. Pop a pair, run the same three checks, and push the pair of left children and the pair of right children.
In Hinglish
Dono trees ko saath-saath chalao: dono null toh same, ek null ya value alag toh false, warna left ko left se aur right ko right se compare karo.