codejump
EasyPythonJavaScriptTypeScript

Binary Tree — Is It Symmetric?

Data StructuresTreesRecursionDFS

Return true when a binary tree is a mirror of itself around its center:
the left subtree must be the mirror image of the right subtree, in both shape
and values.

solve(levelOrder) receives the tree serialized level by level (null = no
child); a builder is provided.

Examples

solve([1, 2, 2, 3, 4, 4, 3])        → true
solve([1, 2, 2, null, 3, null, 3])  → false   // same shape on both sides, not a mirror
solve([1])                          → true
solve([])                           → true

Hint on the shape of the answer: write a helper that compares *two* nodes at
once, recursing on (a.left, b.right) and (a.right, b.left).

Sample tests

Test #1Perfectly mirrored
Input: [[1,2,2,3,4,4,3]]
Output: true
Test #2Same shape on both sides — not a mirror
Input: [[1,2,2,null,3,null,3]]
Output: false
Test #3Single node
Input: [[1]]
Output: true