7. Same Tree
easyAsked at LINEDecide if two binary trees are structurally identical and have equal values at every node — LINE uses this to test recursion clarity before moving into chat-tree replication design.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given the roots of two binary trees p and q, write a function to check if they are the same tree. Two trees are considered the same if they are structurally identical and the nodes have the same value.
Constraints
Number of nodes in each tree is in [0, 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. Brute force serialization
Serialize both trees to strings with null markers, then compare.
- Time
- O(n)
- Space
- O(n)
function serialize(n){ if(!n) return '#'; return n.val+','+serialize(n.left)+','+serialize(n.right); }
return serialize(p)===serialize(q);Tradeoff:
2. Recursive pairwise
Walk both trees in lockstep; at each step compare values and recurse on left and right pairs. Short-circuit on the first mismatch.
- 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:
LINE-specific tips
At LINE, frame this as the diff check you'd run when reconciling a chat-history tree between two devices after offline edits — concrete fan-out language helps.
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 LINE interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →