Skip to main content

11. Symmetric Tree

easyAsked at Ola

Check whether a binary tree mirrors itself around the center.

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

  • Number of nodes is in [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. BFS level compare

BFS level by level and compare the level array against its reverse.

Time
O(n)
Space
O(n)
let q = [root];
while (q.length) {
  const vals = q.map(n => n ? n.val : null);
  if (JSON.stringify(vals) !== JSON.stringify([...vals].reverse())) return false;
  q = q.flatMap(n => n ? [n.left, n.right] : []);
}
return true;

Tradeoff:

2. Mirror DFS

Recursively compare left.left to right.right and left.right to 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 mirror(root.left, root.right);
}

Tradeoff:

Ola-specific tips

Ola uses this to gauge how you set up mirrored recursion arguments; relate it to comparing inbound vs outbound demand grids around a zone center.

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

Practice these live with InterviewChamp.AI →