InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Trees

Symmetric Tree

easy Original ↗ 00:00

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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug