11. Symmetric Tree
easyAsked at OlaCheck whether a binary tree mirrors itself around the 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 (symmetric around its center).
Constraints
Number of nodes is 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. BFS level compare
BFS level by level and compare the level array against its reverse.
- Time
- O(n)
- Space
- O(n)
let q = [root];
while (q.length) {
const vals = q.map(n => n ? n.val : null);
if (JSON.stringify(vals) !== JSON.stringify([...vals].reverse())) return false;
q = q.flatMap(n => n ? [n.left, n.right] : []);
}
return true;Tradeoff:
2. Mirror DFS
Recursively compare left.left to right.right and left.right to right.left.
- 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:
Ola-specific tips
Ola uses this to gauge how you set up mirrored recursion arguments; relate it to comparing inbound vs outbound demand grids around a zone center.
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 Ola interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →