ExamAdda Logo

Same Tree

Easy

Given the roots of two binary trees p and q, determine whether the two trees are the same.

Two binary trees are considered the same if:

  1. They have the same structure.
  2. Corresponding nodes have the same values.

Return true if the trees are identical. Otherwise, return false.

Example 1

Input

p = [1,2,3]
q = [1,2,3]

Output

true

Explanation

Both trees have the same structure and corresponding nodes contain the same values.

Example 2

Input

p = [1,2]
q = [1,null,2]

Output

false

Explanation

Both trees contain the same values, but their structures are different.

Constraints

The number of nodes in each tree is in the range [0
100].
-10^4 <= Node.val <= 10^4

Hints:

Hint 1

Compare the two root nodes first.

Hint 2

If both nodes are null, they are equal. If only one is null, the trees are different.

Author & Technical Reviewer

ExamAdda Technical Review Team

Technically reviewed by: ExamAdda Technical Review Team

Technical Reviewers, ExamAdda

Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.

Published

Aug 11, 2026

Last updated

Aug 12, 2026

Content Verification Methodology

Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.

Report a correction:editorial@examadda.org
Auto
Loading editor...
Input

Expected Output