11. Symmetric Tree
easyAsked at InstacartCheck if a binary tree is a mirror of itself — Instacart picks this as a recursion-pairing warmup ahead of layout-symmetry problems.
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
The number of nodes is in the range [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. Inorder serialize compare
Serialize in-order with positions then check palindrome.
- Time
- O(n)
- Space
- O(n)
const seq = [];
function dfs(n, depth) {
if (!n) { seq.push(`#${depth}`); return; }
dfs(n.left, depth+1); seq.push(n.val+','+depth); dfs(n.right, depth+1);
}
dfs(root, 0);Tradeoff:
2. Mirror recursion
Walk left and right subtrees in mirrored lockstep.
- Time
- O(n)
- Space
- O(h)
function isSymmetric(root) {
function 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:
Instacart-specific tips
Instacart loves the explicit mirror-recursion helper — they'll dig into how you'd transform this into an iterative version for very deep aisle-layout trees.
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 Instacart interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →