Skip to content
Problem 101 · LeetCode 101(opens in a new tab)

Symmetric Tree

EasyRecursion

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.

Try it on LeetCode(opens in a new tab)
  1. Check each level both waysO(n)
  2. Recursive mirror checkO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for a tree of 1,000 nodesVerdict
Check each level both waysO(n)
Passes; builds every level
Recursive mirror checkO(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.left with b.left, which checks that the halves are equal, not mirrored.
  • Dropping empty children when reading a level, so different shapes look symmetric.
  • Reading .val before checking that both nodes exist.

How to talk through it

  1. 1Clarify. Do both shape and values have to mirror? Can the tree have a single node?
  2. 2Reduce it to two trees. The tree is symmetric when its left and right subtrees are mirror images of each other.
  3. 3Name the crossing. Outer with outer (a.left, b.right), inner with inner (a.right, b.left).
  4. 4State the cost. O(n) time and O(h) stack; offer the queue-of-pairs version for the iterative follow-up.
  5. 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?