DSA · Trees · #157
Same Tree
Module 44 · difficulty 2/5·⏱ 30:00starts on first keystroke
Given the roots of two binary trees `p` and `q`, write a function `isSameTree(p, q)` that returns `true` if the trees are structurally identical and every corresponding pair of nodes holds the same value, otherwise `false`. Each node is `{ val, left, right }`; an empty tree is `null`. Two trees are the same when they have the same shape and the same node values at every position.
Examples
p = [1,2,3], q = [1,2,3]→true— Same shape, same values at every node.p = [1,2], q = [1,null,2]→false— Same values present but different structure (left child vs right child).p = [1,2,1], q = [1,1,2]→false— Same shape but mismatched values.
Constraints
- · The number of nodes in each tree is in the range [0, 100].
- · -10^4 <= Node.val <= 10^4
Session phases
A · Clarify
B · Approach
C · Complexity
D · Edges
E · Code
F · Tradeoff
G · Score
Phase A — Clarify
Ask questions about input bounds, types, and edge constraints.
Ask the coach clarifying questions about the problem.
When you've covered this phase, advance to the next.