11. Same Tree
easyAsked at UdemyDecide whether two binary trees are structurally and value-equal — Udemy uses this to test recursive equality before harder course-tree diff problems.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given the roots of two binary trees, return true if they are structurally identical and the nodes have the same values.
Constraints
0 <= nodes in each tree <= 100-10^4 <= Node.val <= 10^4
Examples
Example 1
p=[1,2,3], q=[1,2,3]trueExample 2
p=[1,2], q=[1,null,2]falseApproaches
1. Serialize
Serialize both trees with explicit nulls, then compare strings.
- Time
- O(n)
- Space
- O(n)
function ser(n){ return n ? `(${n.val},${ser(n.left)},${ser(n.right)})` : '#'; }
return ser(p) === ser(q);Tradeoff:
2. Recurse pairs
If both null, equal. If only one null, unequal. Else compare values and recurse on left and right pairs.
- Time
- O(n)
- Space
- O(h)
function isSameTree(p, q) {
if (!p && !q) return true;
if (!p || !q || p.val !== q.val) return false;
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}Tradeoff:
Udemy-specific tips
Udemy interviewers like to extend this to diffing two versions of a course outline — show you handle null branches before touching values.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Same 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 →