InterviewPrepKit

Home / Coding / Trees

Symmetric Tree

easy Original โ†—
Solving tips
  • Reframe as mirror-equality of two trees: the root's left subtree versus its right subtree via a helper isMirror(a, b).
  • The one twist versus Same Tree: cross the children, pairing a.left with b.right and a.right with b.left; that cross IS the whole problem.
  • Same three-case skeleton: both None (match), one None (fail), else compare values and recurse on crossed pairs.
  • O(n) time, O(h) space; the iterative follow-up uses a queue of pairs, preserving the crossed enqueue order.

Problem

Given the root of a binary tree, decide whether the tree is a mirror of itself โ€” that is, symmetric around its vertical center line. Return True if it is, False otherwise.

Symmetry is both structural and value-based: the left subtree must be the mirror image of the right subtree, with matching values at mirrored positions.

Examples

Example 1

Input: root = [1,2,2,3,4,4,3]
Output: True

Left subtree (2 โ†’ 3,4) is the mirror of the right subtree (2 โ†’ 4,3): outer children 3/3 match, inner children 4/4 match.

Example 2

Input: root = [1,2,2,null,3,null,3]
Output: False

Both 2s have their 3 as a right child. Mirrored positions would require one 3 on the right and the other on the left.

Example 3

Input: root = [1]
Output: True

A single node (and likewise an empty tree) is trivially symmetric.

Constraints

  • The number of nodes is in the range [1, 1000].
  • -100 <= Node.val <= 100

Follow-up: solve it both recursively and iteratively.

Think about it first

Hint 1 "The tree is symmetric" is really a statement about two trees: the root's left subtree and the root's right subtree. What relation must hold between them?
Hint 2 Write a helper `isMirror(a, b)`. When comparing a's children to b's children, which child of a pairs with which child of b?
Hint 3 Two trees mirror each other iff both are None, or both exist with equal values, a's LEFT mirrors b's RIGHT, and a's RIGHT mirrors b's LEFT. It's the Same Tree recursion with the second tree's children crossed.
Your workspace Not runnable by design โ€” this is your interview scratchpad. Saved on this device.