Same Tree
Part of Practice: Recursive Foundations
You are given the roots of two binary trees, p and q. Decide whether the two trees are identical: they must have exactly the same shape, and the nodes in matching positions must hold equal values. Return true or false.
Each tree has at most 100 nodes. Either tree can be empty; two empty trees count as the same.
Examples
- Input:
- p = [1,2,3], q = [1,2,3]
- Output:
- true
- Input:
- p = [1,2], q = [1,null,2]
- Output:
- false
The values are the same but the shapes differ: in p the 2 is a left child, in q it is a right child.
- Input:
- p = [1,2,1], q = [1,1,2]
- Output:
- false
Same shape, but the children's values are swapped.
Hints
One at a time — struggle first, peek second.
Your thinking space — verify on LeetCode, then mark it.