Skip to main content

11. Symmetric Tree

easyAsked at Indeed

Decide whether a binary tree is a mirror of itself — Indeed's mirror-recursion warmup before bidirectional graph matching problems.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given the root of a binary tree, check whether it is a mirror of itself around its center. Subtrees must mirror each other in structure and node values.

Constraints

  • 1 <= nodes <= 1000
  • -100 <= node.val <= 100

Examples

Example 1

Input
root = [1,2,2,3,4,4,3]
Output
true

Example 2

Input
root = [1,2,2,null,3,null,3]
Output
false

Approaches

1. Inorder serialize

Compare inorder traversal against its reverse.

Time
O(n)
Space
O(n)
const inorder = (n) => n ? [...inorder(n.left), n.val, ...inorder(n.right)] : ['#'];
const arr = inorder(root);
return arr.join() === arr.slice().reverse().join();

Tradeoff:

2. Mirror recursion

Pair left and right subtrees, recursing into outer and inner pairs.

Time
O(n)
Space
O(h)
function isSymmetric(root) {
  const mirror = (a, b) => {
    if (!a && !b) return true;
    if (!a || !b) return false;
    return a.val === b.val
      && mirror(a.left, b.right)
      && mirror(a.right, b.left);
  };
  return !root || mirror(root.left, root.right);
}

Tradeoff:

Indeed-specific tips

Indeed grades for the careful left-right pairing — connect it to comparing mirrored job-clusters across geographic markets.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Symmetric Tree and other Indeed interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →