11. Same Tree
easyAsked at CourseraDecide if two binary trees are structurally identical — Coursera tests recursive structural compare for course-tree diffing.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given the roots of two binary trees p and q, return true if they are structurally identical and have the same node values.
Constraints
0 <= nodes <= 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 and compare
Preorder serialize both with null markers, compare strings.
- Time
- O(n)
- Space
- O(n)
const ser = (n) => n ? `${n.val},${ser(n.left)},${ser(n.right)}` : '#';
return ser(p) === ser(q);Tradeoff:
2. Recursion
Compare both nulls, then values, then recurse children.
- Time
- O(n)
- Space
- O(h)
function isSameTree(p, q) {
if (!p && !q) return true;
if (!p || !q) return false;
if (p.val !== q.val) return false;
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}Tradeoff:
Coursera-specific tips
Coursera asks you to handle the null-vs-null base case first — they have seen candidates flunk by forgetting the (!p && !q) case in their course-tree compare ETL.
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 Coursera interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →