7. Symmetric Tree
easyAsked at MercuryDetermine 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, check whether it is a mirror of itself. A tree is symmetric if its left subtree is a structural mirror of its right subtree with matching values.
Constraints
Node count in [1, 1000]-100 <= Node.val <= 100
Examples
Example 1
root = [1,2,2,3,4,4,3]trueExample 2
root = [1,2,2,null,3,null,3]falseApproaches
1. Iterative pair queue
Enqueue mirrored pairs and compare values per pop.
- Time
- O(n)
- Space
- O(n)
const q=[[root.left,root.right]];
while(q.length){const [a,b]=q.shift();
if(!a&&!b) continue; if(!a||!b||a.val!==b.val) return false;
q.push([a.left,b.right],[a.right,b.left]);}
return true;Tradeoff:
2. Mirror recursion
Recurse comparing left-of-left vs right-of-right and left-of-right vs right-of-left. Linear in nodes.
- Time
- O(n)
- Space
- O(h)
function isSymmetric(root) {
const mirror = (a, b) => {
if (!a && !b) return true;
if (!a || !b || 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:
Mercury-specific tips
Mercury frames symmetry checks as verifying that ACH credit and debit halves of an internal book-transfer mirror each other — drift one side and reconciliation breaks.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Symmetric Tree and other Mercury interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →