Given the root of a binary tree, return true if it is symmetric — a mirror image of itself around its center — and false otherwise.
The tree is given in level-order (breadth-first), using null for missing children.
Input: root = [1, 2, 2, 3, 4, 4, 3] Output: true The left and right subtrees are mirror images of each other.
Input: root = [1, 2, 2, null, 3, null, 3] Output: false The 3s are both on the inner side rather than mirrored, breaking symmetry.
- The number of nodes is in the range [1, 1000] - -100 <= Node.val <= 100
A tree is symmetric when its left subtree is the mirror of its right subtree. Two subtrees mirror each other when their roots are equal and — the key twist — the outer children match (a.left with b.right) and the inner children match (a.right with b.left). It's the same-tree comparison with the recursion crossed.
“Symmetric by structure and values?”
Both — the mirror must match in shape and in node values.
“Is an empty tree symmetric?”
Yes, trivially.
A tree is symmetric if its left and right subtrees are mirror images.
Two subtrees mirror when their roots are equal and the outer pair (a.left vs b.right) and inner pair (a.right vs b.left) also mirror.
Worked example — tree [1, 2, 2, 3, 4, 4, 3]
1
/ \
2 2
/ \ / \
3 4 4 3
mirror(2,2): outer 3 vs 3 ✓, inner 4 vs 4 ✓
answer: true
The whole check reduces to one call: mirror(root.left, root.right).
Mirror compares a.left with b.right and a.right with b.left — the crossing is what encodes 'mirror image'.
Swap the two recursive pairings back to (left,left) and (right,right) and you get the same-tree check.
| Iterative (queue of mirrored pairs) | Recursive mirror | |
|---|---|---|
| Idea | Compare outer/inner pairs from a queue | roots equal AND outer mirror AND inner mirror |
| Time | O(n) | O(n) |
| Space | O(n) | O(height) |
Both are O(n); the recursion is a direct transcription. Full code is in the Approaches selector below.
Key takeaway
A tree is symmetric iff its left subtree mirrors its right. Two subtrees mirror when roots are equal and outer (a.left↔b.right) and inner (a.right↔b.left) pairs mirror. O(n) time, O(height) space.
mirror(a, b):
if a is null and b is null: return true
if a is null or b is null or a.val != b.val: return false
return mirror(a.left, b.right) and mirror(a.right, b.left)