Example 1
- Input
- p = [1,2,3], q = [1,2,3]
- Output
- true
Both trees place 1 at the root with 2 left and 3 right.
Given the roots of two binary trees p and q, return true when both trees share the same structure and the same values at every position. Two empty trees count as identical.
Given the roots p and q of two binary trees, check whether they are the same tree.
Two trees are the same when they are structurally identical and every pair of nodes in matching positions holds equal values. Two empty trees are the same.
0 and 100 nodes.null for a missing child.Both trees place 1 at the root with 2 left and 3 right.
Both roots are absent. There is no position at which shape or value differs, so two empty trees match.
2 is a left child in p but a right child in q, so the structures differ.
The shapes match but the children hold swapped values.
Equal roots are only the first check: every left and right position must also agree. In Example 1, pair 1 with 1, then 2 with 2 and 3 with 3; the empty child slots must match too. Equal values reached in different positions do not make identical trees.
Reveal Pair Queue Check: intuition, complexity, and code
.val before ruling out empty nodes, which crashes on the first missing child.true after the roots match without checking the subtrees below.[1,2] and [1,null,2] both visit values 1,2.Dual-tree questions stay aligned by carrying both nodes together, whether as a recursive pair of arguments or as pairs in a queue.