LeetCode #101 Easy

Symmetric Tree

Symmetric Tree is LeetCode 101 (Easy). Given the root of a binary tree, return true if the tree is a mirror of itself around its centre, and false otherwise.

  • The two halves must match in shape as well as in values.
  • The tree has 1 to 1,000 nodes with values from -100 to 100.
  • The follow-up asks for both a recursive and an iterative solution.
Constraints
  • The number of nodes in the tree is in the range [1, 1000].
  • -100 <= Node.val <= 100
treedfsrecursion
Open on LeetCode ↗
02

Intuition

Fold the tree down the middle. It is symmetric when every node on the left half lands on a node with the same value on the right half, so the real question is about two nodes at a time: a left node and the node in its mirrored spot.

  • Mirrored spots cross: the partner of a left child is a right child. Below a matching pair, the two outer children pair up, and so do the two inner ones.
  • Each pair is settled on its own: two empty spots match, one empty spot breaks the shape, and two nodes need equal values.

Start with the root's two children. The tree is symmetric only if every pair passes.

How to spot this pattern

When a question compares a tree with its own reflection, write a helper that takes two nodes and recurse with the children crossed.

03

Approach

Try it first

Before reading on, take the root's two children as a pair. Decide when that pair passes, and which two pairs of grandchildren you must check next. Aim for one visit per node.

1

Start from the root's two children

Call mirror(root.left, root.right). The root sits on the fold line, so it has no partner; only its children have to reflect each other. A one-node tree passes at once, because both children are missing.

2

Settle missing nodes before reading values

If both nodes are null, return true: two empty spots mirror each other. If exactly one is null, return false: one side has a node where the other has none. Both checks run before .val is read, so a null is never dereferenced.

3

Compare the two values

With both nodes present, return false when a.val != b.val. The two nodes sit in mirrored spots, so a symmetric tree must hold the same value in both of them.

4

Check the outer pair, then the inner pair

Return mirror(a.left, b.right) and mirror(a.right, b.left). The children cross because a reflection swaps left and right. The and skips the inner pair when the outer pair already failed, so the first mismatch anywhere ends the walk.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def isSymmetric(self, root):
▶3 def mirror(a, b):
▶4 if not a and not b:
▶5 return True
▶6 if not a or not b:
▶7 return False
▶8 if a.val != b.val:
▶9 return False
▶10 return mirror(a.left, b.right) and mirror(a.right, b.left)
▶11 
▶12 return not root or mirror(root.left, root.right)
fold1223443left spotright spotno pair yetpairs waitingnoneroot sits on the fold → check its two children
pair2 and 2root's left and right child
The root 1 lies on the centre line, so it has no partner to match. The tree is symmetric exactly when the root's left child mirrors its right child, so that pair is checked first.
fold1223443left spotright spot2=2pairs waiting442 and 2 match → check outer pair, then inner
values2 = 2
next3 and 3outer pair
Both spots hold 2, so this pair passes. Their children must cross: the outer pair is this left node's left child with the right node's right child, and the inner pair is the two children nearest the fold. The inner pair waits while the outer one is checked.
fold1223443left spotright spot3=3pairs waiting443 and 3 match → check outer pair, then inner
values3 = 3
nextempty and emptyouter pair
Both spots hold 3, so this pair passes. Their children must cross: the outer pair is this left node's left child with the right node's right child, and the inner pair is the two children nearest the fold. The inner pair waits while the outer one is checked.
fold1223443left spotright spot=pairs waiting44both spots empty → this pair is fine
pairempty and empty
Neither side has a node here, and two empty spots are mirror images of each other. This pair passes without reading any value. Next comes the pair that was waiting.
fold1223443left spotright spot=pairs waiting44both spots empty → this pair is fine
pairempty and empty
Neither side has a node here, and two empty spots are mirror images of each other. This pair passes without reading any value. Next comes the pair that was waiting.
fold1223443left spotright spot4=4pairs waiting4 and 4 match → check outer pair, then inner
values4 = 4
nextempty and emptyouter pair
Both spots hold 4, so this pair passes. Their children must cross: the outer pair is this left node's left child with the right node's right child, and the inner pair is the two children nearest the fold. The inner pair waits while the outer one is checked.
fold1223443left spotright spot=pairs waitingboth spots empty → this pair is fine
pairempty and empty
Neither side has a node here, and two empty spots are mirror images of each other. This pair passes without reading any value. Next comes the pair that was waiting.
fold1223443left spotright spot=pairs waitingnoneboth spots empty → this pair is fine
pairempty and empty
Neither side has a node here, and two empty spots are mirror images of each other. This pair passes without reading any value.
fold1223443left spotright spotall pairs checkedpairs waitingnoneevery pair matched → true
resulttrue
Every mirrored pair passed, including the empty spots below the leaves, so the tree folds onto itself: the answer is true. Each node was looked at once, as part of exactly one pair.
05

Queue of pairs

The queue holds pairs of nodes that must mirror each other, starting with the root's two children. Each loop takes one pair and applies the same three checks. A passing pair adds its outer pair and its inner pair to the queue. In Java, use LinkedList here: ArrayDeque throws on null, and missing children are pushed as nulls.

▶1from collections import deque
▶2 
▶3class Solution:
▶4 def isSymmetric(self, root):
▶5 if not root:
▶6 return True
▶7 q = deque([(root.left, root.right)])
▶8 while q:
▶9 a, b = q.popleft()
▶10 if not a and not b:
▶11 continue
▶12 if not a or not b or a.val != b.val:
▶13 return False
▶14 q.append((a.left, b.right))
▶15 q.append((a.right, b.left))
▶16 return True
06

Common pitfalls

Pairing left with left

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

Uncrossed calls test whether the two halves are copies, not reflections. On [1,2,2,3,4,4,3], which is symmetric, the left half's 3 gets compared with the right half's 4, so the code returns false.

Checking that a traversal reads the same both ways

✗ Wrong
vals = inorder(root)
return vals == vals[::-1]
✓ Right
return mirror(root.left, root.right)

A list of values forgets where the empty spots are. [1,2,2,2,null,2] has inorder 2, 2, 1, 2, 2, a palindrome, yet both lower 2s hang on the left. Checking each level for a palindrome while skipping nulls fails the same way on [1,2,2,null,3,null,3].

07

Edge cases

Only one child under the root, [1,2]

The first pair is 2 against an empty spot, so the one-null check returns false before any value is compared.

Equal values, different shape, [1,2,2,null,3,null,3]

The pair of 2s passes, but the outer pair below them is an empty spot against a 3, so the answer is false. Values alone never catch this.

08

Complexity

Time
O(n)
Space
O(h)
Each call handles one mirrored pair, so every node is read once. The recursion goes as deep as the tree is tall; a tree with one long arm fails at its first unmatched pair, so a symmetric tree here is at most about 500 levels deep.
09

Symmetric Tree FAQ

How is this different from Same Tree?

Same Tree walks two separate trees and pairs left with left. Here there is one tree, and each node is paired with its reflection, so the left child of one node meets the right child of the other.

Can I mirror the tree and then compare it with the original?

Yes. Invert a copy of the tree and run the Same Tree check on the two. It is correct, but it builds a second tree with O(n) extra memory, while the pair check does the same comparison without building anything.

Is a symmetric tree also a complete one?

Not necessarily; the two ideas are unrelated. [1,2,2,null,3,3] is symmetric but not complete, and [1,2,3] is complete but not symmetric. Symmetry only asks that mirrored spots agree.