Skip to main content

11. Symmetric Tree

easyAsked at Quora

Check if a binary tree is a mirror image of itself.

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

Problem

Given the root of a binary tree, return true if it is a mirror of itself — the left subtree is the mirror image of the right subtree.

Constraints

  • 0 <= 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 against reverse

Collect inorder twice with mirrored direction and compare.

Time
O(n)
Space
O(n)
// gather left-root-right and right-root-left, then compare arrays
// fails on null-shape mismatches without sentinels

Tradeoff:

2. Recursive mirror check

Pair left.left with right.right and left.right with right.left.

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

Tradeoff:

Quora-specific tips

Quora uses mirror-structure tests because their merged-question detector compares thread shapes from two sources and rejects pairs whose nesting symmetry doesn't line up.

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

Practice these live with InterviewChamp.AI →