🔍 Problem
Determine whether two binary trees are structurally identical.
A pair of sub-trees are considered identical when
- They are both empty, or
- Both roots exist, carry the same value, and their left/right sub-trees are themselves identical.
(If you only care about shape and not the stored values, drop the value check—that’s one tiny edit.)
🌳 Recursive “One-Liner” Idea
⚙️ identical(A, B) =
A and B are both None ✅
or A and B both exist
and A.val == B.val
and identical(A.left, B.left)
and identical(A.right, B.right)
🐍 Python Implementation
class Node:
def __init__(self, val, left=None, right=None):
self.val, self.left, self.right = val, left, right
def are_identical(root1: Node | None, root2: Node | None) -> bool:
"""Return True iff the two binary trees are structurally (and value) identical."""
if root1 is root2: # covers simultaneous None
return True
if not root1 or not root2: # exactly one is None
return False
return (root1.val == root2.val and
are_identical(root1.left, root2.left) and
are_identical(root1.right, root2.right))
Complexity
• Time: O(n) — each node visited once (where n = min(#nodes of both trees) if sizes equal).
• Space: O(h) call-stack, h = tree height (log n for balanced, n worst-case).
🔁 Iterative (Stack) Version
Sometimes you want to avoid recursion depth issues:
def are_identical_iter(root1, root2):
stack = [(root1, root2)]
while stack:
n1, n2 = stack.pop()
if n1 is n2:
continue # both None
if not n1 or not n2 or n1.val != n2.val:
return False
stack.append((n1.left, n2.left))
stack.append((n1.right, n2.right))
return True
Same asymptotic complexities, but uses an explicit stack (O(h)).
💡 If You ONLY Care About Shape
Just delete the value check:
if not n1 or not n2: return False # unchanged
# ↓ remove this ↓
# and n1.val == n2.val
That’s it! 🎉