Skip to main content

11. Symmetric Tree

easyAsked at DigitalOcean

Determine if a binary tree is a mirror of itself around its center — DigitalOcean uses this to assess paired-recursion fluency that surfaces in cross-region failover-pair validation.

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. Return true if symmetric.

Constraints

  • 1 <= number of 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

Serialize the tree, check if the string is a palindrome.

Time
O(n)
Space
O(n)
function ser(n){return n? '('+ser(n.left)+n.val+ser(n.right)+')' : '_'}
const s = ser(root);
return s === s.split('').reverse().join('');

Tradeoff:

2. Mirror recursion

Compare left.left with right.right and left.right with right.left simultaneously.

Time
O(n)
Space
O(h)
function isSymmetric(root) {
  const 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:

DigitalOcean-specific tips

DigitalOcean grades the mirror-recursion version higher because it short-circuits on the first asymmetry — important when validating that paired region replicas match without serializing the entire topology.

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

Practice these live with InterviewChamp.AI →