Skip to main content

10. Symmetric Tree

easyAsked at SoFi

Determine if a binary tree is a mirror of itself — SoFi uses this to gauge tree-recursion intuition before scaling up to portfolio-balance trees.

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

  • Number of nodes is in range [1, 1000]
  • -100 <= Node.val <= 100

Examples

Example 1

Input
[1,2,2,3,4,4,3]
Output
true

Example 2

Input
[1,2,2,null,3,null,3]
Output
false

Approaches

1. Brute force

BFS each level and check if level array is palindromic, handling nulls explicitly.

Time
O(n)
Space
O(n)
function isSymmetric(root) {
  let q = [root];
  while (q.length) {
    const vals = q.map(n => n ? n.val : null);
    for (let i = 0; i < vals.length/2; i++)
      if (vals[i] !== vals[vals.length-1-i]) return false;
    q = q.flatMap(n => n ? [n.left, n.right] : []);
  }
  return true;
}

Tradeoff:

2. Recursive mirror check

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;
    return a.val === b.val
      && mirror(a.left, b.right)
      && mirror(a.right, b.left);
  };
  return mirror(root?.left, root?.right);
}

Tradeoff:

SoFi-specific tips

SoFi engineers care about explicit null handling because brokerage account trees often have sparse branches (no joint owner, no beneficiary) and crashing on null = lost trade.

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

Practice these live with InterviewChamp.AI →