Skip to main content

11. Symmetric Tree

easyAsked at Chegg

Detect mirror symmetry in a binary tree — Chegg uses this to test mirrored-recursion comfort on layout symmetry checks.

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

Problem

Given the root of a binary tree, check whether it is a mirror of itself (symmetric around its center).

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 string compare

Compare inorder traversal against its reverse.

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

Tradeoff:

2. Pair recursion

Recurse with mirrored children: left.left vs right.right, left.right vs right.left.

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:

Chegg-specific tips

Chegg interviewers expect the pair-recursion answer because it generalizes to their UI layout mirror-checks where left and right siblings must mirror without allocating intermediate arrays.

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 Chegg interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →