Practice · Trees · 3 of 12

Identical Binary Trees

You are given p and q, the roots of two binary trees (either may be empty).

Return true if the trees are identical, with the same shape and equal values in matching places, and false otherwise.

Trees are written in level order, row by row from the top, with null where a node is missing: [4, 2, 7, null, 3] is 4 at the root, 2 and 7 below it, and 3 as the right child of 2.

Example 1

Input
p = [4, 2, 6, 1, 3], q = [4, 2, 6, 1, 3]
Output
true

Example 2

Input
p = [7, 5], q = [7, null, 5]
Output
false
The values match, but 5 is a left child in one tree and a right child in the other.

Constraints

  • Each tree holds 0 to 500 nodes.
  • Every value is between −10⁴ and 10⁴.