LeetCode #101 Easy

Symmetric Tree

Is the tree a mirror of itself around its center?

treedfsrecursion
Open on LeetCode ↗
02

Intuition

Symmetry is Same Tree with a twist: compare the left subtree against the mirrored right subtree. So the recursion pairs a.left with b.right and a.right with b.left.

How to spot this pattern

Symmetry is same-tree with one pairing changed. Instead of comparing left-to-left, you compare each subtree against its mirror — left against right. Whenever a problem is about reflection rather than equality, look for the place where the recursive call's arguments should cross over.

03

Approach

1

Mirror comparison

mirror(a, b) = a.val == b.val AND mirror(a.left, b.right) AND mirror(a.right, b.left).

2

Start with the root's children

The root always mirrors itself; the question is mirror(root.left, root.right).

3

Iterative variant

A queue of node pairs does the same pairing breadth-first — useful when recursion depth is a worry.

04

Solution & live demo

1class Solution:
2 def isSymmetric(self, root):
3 def mirror(a, b):
4 if not a and not b: return True
5 if not a or not b: return False
6 return (a.val == b.val
7 and mirror(a.left, b.right)
8 and mirror(a.right, b.left))
9 return not root or mirror(root.left, root.right)
05

Common pitfalls

Recursing on matching sides instead of mirrored ones

✗ Wrong
return (a.val == b.val
        and mirror(a.left, b.left)
        and mirror(a.right, b.right))
✓ Right
return (a.val == b.val
        and mirror(a.left, b.right)
        and mirror(a.right, b.left))

That tests whether the two subtrees are identical, not mirrored — it would reject [1,2,2,3,4,4,3], which is symmetric. A reflection maps the leftmost node to the rightmost, so the calls must cross.

Comparing the root with itself

✗ Wrong
return mirror(root, root)
✓ Right
return not root or mirror(root.left, root.right)

It happens to work, because crossing the arguments makes the root trivially match itself — but it obscures the actual claim, which is that the root's two children are mirrors of each other. Starting from the children states the invariant you're relying on.

06

Edge cases

[1,2,2,null,3,null,3]

Shape matches but not mirrored (both 3s on the same side) → False — the cross-pairing catches it.

Empty tree

Symmetric by convention → True.

07

Complexity

Time
O(n)
Space
O(h)
Each node visited once in a pair.