Same Tree
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:
- They have the same structure.
- 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
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
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.
Expected Output