CodingNodes / Trees / Symmetric Tree System design Space play · ←→ step · R restart

Problem

Given the root of a binary tree, return true if the tree is a mirror image of itself: its left half, flipped around the middle, looks exactly like its right half, values included.

The tree is given in level order, with null for a missing child.

Constraints

  • 1 ≤ number of nodes ≤ 1000
  • -100 ≤ Node.val ≤ 100

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(h)

Time: Each node takes part in exactly one pair comparison.

Space: The recursion goes as deep as the tree is tall, h. That is log n for a balanced tree and n for a chain.

Two subtrees are mirrors if their roots hold the same value, the outer children mirror each other (left of one against right of the other), and the inner children mirror each other. Start with the root's two children and recurse. Two empty spots match, and one empty spot against a node does not.