You are given the root of a binary tree. Decide whether the tree is symmetric: whether its left half is a mirror image of its right half.
Picture a vertical line through the root. The tree is symmetric when folding it along that line puts every node on top of a node with the same value, and every empty spot on top of an empty spot. Return true or false.
Example 1
Input: root = [6, 3, 3, 8, 5, 5, 8] Output: true Why: the outer 8s match and the inner 5s match
2 more examples and the constraints
Example 2
Input: root = [2, 5, 5, 1, null, 1] Output: false Why: both 1s hang on the left; a mirror needs one on the right
Example 3
Input: root = [4] Output: true Why: a single node is its own mirror
Constraints
- The tree has between 1 and 1,000 nodes
- −100 ≤ each node value ≤ 100
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Check each level both waysO(n)
- Recursive mirror checkO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for a tree of 1,000 nodes | Verdict |
|---|---|---|---|
| Check each level both ways | O(n) | Passes; builds every level | |
| Recursive mirror check | O(n) | Best; each pair checked once |
n = number of nodes, w = widest level, h = height of the tree.
Edge cases to test
- A single node. [4] has two empty sides, which mirror each other: return true.
- Only one child. [1, 2] has a node on the left and a gap on the right: return false.
- Right values, wrong pairing. [1, 2, 2, 3, 4, 3, 4] has the same values on both sides, but the outer 3 faces an outer 4.
- Same values, uneven shape. [2, 5, 5, 1, null, 1] has matching values, but both 1s are left children, so the shapes do not mirror.
Common mistakes
- Comparing
a.leftwithb.left, which checks that the halves are equal, not mirrored. - Dropping empty children when reading a level, so different shapes look symmetric.
- Reading
.valbefore checking that both nodes exist.
How to talk through it
- 1Clarify. Do both shape and values have to mirror? Can the tree have a single node?
- 2Reduce it to two trees. The tree is symmetric when its left and right subtrees are mirror images of each other.
- 3Name the crossing. Outer with outer (
a.left,b.right), inner with inner (a.right,b.left). - 4State the cost. O(n) time and O(h) stack; offer the queue-of-pairs version for the iterative follow-up.
- 5Test out loud. Run a single node, a node with only one child, and a tree with the right values in the wrong places.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?