Skip to main content

11. Symmetric Tree

easyAsked at Instacart

Check if a binary tree is a mirror of itself — Instacart picks this as a recursion-pairing warmup ahead of layout-symmetry 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 (i.e., symmetric around its center).

Constraints

  • The number of nodes is in the range [1, 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

Serialize in-order with positions then check palindrome.

Time
O(n)
Space
O(n)
const seq = [];
function dfs(n, depth) {
  if (!n) { seq.push(`#${depth}`); return; }
  dfs(n.left, depth+1); seq.push(n.val+','+depth); dfs(n.right, depth+1);
}
dfs(root, 0);

Tradeoff:

2. Mirror recursion

Walk left and right subtrees in mirrored lockstep.

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

Tradeoff:

Instacart-specific tips

Instacart loves the explicit mirror-recursion helper — they'll dig into how you'd transform this into an iterative version for very deep aisle-layout trees.

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

Practice these live with InterviewChamp.AI →