EasyTreeDepth-First SearchBreadth-First SearchBinary Tree

1 approach, code in every language

Problem description

Given the root of a binary tree, decide whether the tree is a mirror image of itself around its center. In other words, check whether the left subtree is the reflection of the right subtree.

A tree is symmetric when reflecting it left-to-right produces an identical shape and identical values. This is different from the two subtrees merely being equal; the comparison must be done in mirrored order.

Example 1

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

Output: true

The left subtree [2,3,4] mirrors the right subtree [2,4,3]: matching outer children (3 vs 3) and matching inner children (4 vs 4).

Example 2

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

Output: false

Both children of the root are 2, but a mirror requires the left node's right child (3) to match the right node's left child, which is null. One side has the node and the other is missing it, so the mirror alignment breaks.

Constraints

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

After the pattern

Now solve one you haven't seen.

Chime Hangs True is our own problem on the technique behind Symmetric Tree: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free