AlgoFrames

Same tree

Standard · Write code · about 8 min

Given the roots p and q of two binary trees, return true when they are the same tree: the same shape, with equal values in every position.

Example 1

Input:

[[1,2,3],[1,2,3]]

Output:

true

Example 2

Input:

[[1,2],[1,null,2]]

Output:

false

The values match, but 2 is a left child in p and a right child in q.

Constraints

  • 0 ≤ number of nodes ≤ 1,000
  • -1,000 ≤ Node.val ≤ 1,000
  • The tree is given in level order; null marks a missing child

Learn the idea first: Recursive problems on trees: height, size, mirror, paths, a visual lesson.

More Recursive problems on trees: height, size, mirror, paths problems