Skip to main content

12. Symmetric Tree

easyAsked at Duolingo

Determine if a binary tree is a mirror of itself around its center.

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

Problem

Given the root of a binary tree, return true if the tree is symmetric (left subtree is a mirror of the right subtree).

Constraints

  • 1 <= node count <= 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

Walk inorder and compare with reverse-inorder string—fails for value collisions.

Time
O(n)
Space
O(n)
function inorder(n,arr){ if(!n){arr.push('#');return;} inorder(n.left,arr); arr.push(n.val); inorder(n.right,arr); }

Tradeoff:

2. Mirror DFS pair

Recurse on (left.left, right.right) and (left.right, right.left). Values must match and both sides must mirror.

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:

Duolingo-specific tips

Duolingo A/B-tests symmetric variants of skill trees; the paired-mirror DFS is the exact check used to confirm two arms of an experiment match in shape.

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

Practice these live with InterviewChamp.AI →