22. Symmetric Tree
easyAsked at GitHubCheck whether a binary tree is a mirror of itself using recursive or iterative paired traversal, a BFS/DFS tree skill GitHub tests in screening rounds.
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
The number of nodes is in 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. Serialize and string compare
Serialize left and right subtrees then compare — verbose and allocates O(n) strings unnecessarily.
- Time
- O(n)
- Space
- O(n)
// serialize(left) === serialize(mirror of right)
// Works but extra allocation and code complexityTradeoff:
2. Recursive mirror check
Define a helper isMirror(left, right) that checks outer pairs (left.left vs right.right) and inner pairs (left.right vs right.left) recursively.
- Time
- O(n)
- Space
- O(h)
function isSymmetric(root) {
function isMirror(l, r) {
if (!l && !r) return true;
if (!l || !r) return false;
return l.val === r.val &&
isMirror(l.left, r.right) &&
isMirror(l.right, r.left);
}
return isMirror(root.left, root.right);
}Tradeoff:
GitHub-specific tips
GitHub screens with this problem to verify clean recursive thinking; also be ready with the iterative BFS queue variant pairing nodes level-by-level, since interviewers often ask for both.
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 GitHub interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →