12. Symmetric Tree
easyAsked at UdemyCheck whether a binary tree is a mirror of itself — a Udemy warm-up that tests recursive thinking around tree structure.
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). Return true if the tree is symmetric, false otherwise.
Constraints
1 <= number of nodes <= 1000Node values fit in a 32-bit integer
Examples
Example 1
root = [1,2,2,3,4,4,3]trueExample 2
root = [1,2,2,null,3,null,3]falseApproaches
1. Brute force
Serialize left and right subtrees and compare the strings.
- Time
- O(n)
- Space
- O(n)
// serialize both halves and compare — works but uses extra space
function isSymmetric(root) {
const left = serialize(root.left);
const right = serialize(root.right);
return left === reverse(right);
}Tradeoff:
2. Recursive mirror check
Recursively compare outer and inner pairs of nodes simultaneously, mirroring left.left with right.right and left.right with right.left.
- Time
- O(n)
- Space
- O(h)
function isSymmetric(root) {
function isMirror(left, right) {
if (!left && !right) return true;
if (!left || !right) return false;
return left.val === right.val
&& isMirror(left.left, right.right)
&& isMirror(left.right, right.left);
}
return isMirror(root.left, root.right);
}Tradeoff:
Udemy-specific tips
Udemy asks about e-learning recommendation systems, content search, and marketplace algorithms — balanced mix of arrays, hash maps, and dynamic programming problems.
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 Udemy interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →