Symmetric Tree

Check whether a binary tree is a mirror of itself - left subtree mirrors the right subtree at every level.

Recursive DFSMirror CheckBFS VariantEasy

Key concepts at a glance — for those who already know the basics.


Given the root of a binary tree, determine whether it is symmetric around its center.

Symmetric means left and right subtrees are mirror images with matching structure and matching values at mirrored positions.

Example: [1,2,2,3,4,4,3] => true, [1,2,2,null,3,null,3] => false

A tree is symmetric if its left and right subtrees are mirrors of each other

Two subtrees are mirrors when: their roots have equal values, the left child of one equals the right child of the other, and vice versa - checked recursively all the way down.

1
Start with the root's two children
Call a helper isMirror(left, right) with root.left and root.right.
2
Check the base cases first
Both None -> symmetric. One None, one not -> asymmetric. Both exist -> compare values.
3
Recurse with the outer and inner pairs
Outer: left.left vs right.right. Inner: left.right vs right.left. Both must pass.
4
Return True only when values match AND both recursive calls pass
Any mismatch anywhere in the subtree short-circuits the whole check to False.
def isSymmetric(root) -> bool:
 
def isMirror(left, right) -> bool:
if not left and not right: # both None -> symmetric
return True
if not left or not right: # one None -> not symmetric
return False
 
return (
left.val == right.val # values match
and isMirror(left.left, right.right) # outer pair
and isMirror(left.right, right.left) # inner pair
)
 
return isMirror(root.left, root.right)
mirror axis outer pair inner pair 1 2 2 3 4 4 3 Output: True (symmetric)
Call
left
right
Result
isMirror(2, 2)
node(2)
node(2)
2==2, recurse
isMirror(3, 3)
node(3)
node(3)
3==3, both children None => True
isMirror(4, 4)
node(4)
node(4)
4==4, both children None => True
Final
-
-
True - tree is symmetric
Time
O(n)
Every node is visited exactly once in mirror comparisons.
Space
O(h)
Call stack depth equals tree height h.

Try it yourself

LeetCode 101 · Easy · Tags: Tree, DFS, BFS, Binary Tree

Open on LeetCode ↗