easyTreesPure DSA~12 min
Replica Tree Equal
Two replicas of a category hierarchy must be byte-for-byte identical after a sync. Verify the two trees have the same shape and the same node values at every position.
Problem
Given the roots of two binary trees p and q, return true if they are structurally identical and every corresponding pair of nodes has the same value, and false otherwise.
Input
Two binary tree roots p and q (0 ≤ nodes ≤ 100 each).
Output
A boolean — true if the trees are identical.
Constraints
- Either tree may be empty
- Node values fit in a 32-bit integer
- Structure and values must both match
Examples
Example 1
Input
p = [1,2,3], q = [1,2,3]
Output
true
Same shape, same values.
Example 2
Input
p = [1,2], q = [1,null,2]
Output
false
The 2 is a left child in p but a right child in q.