Given the roots of two binary trees p and q, write a function to check if they are the same or not.

Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.

Input & Output

Example 1 — Identical Trees
$ Input: p = [1,2,3], q = [1,2,3]
Output: true
💡 Note: Both trees have the same structure: root 1 with left child 2 and right child 3. All corresponding nodes have identical values.
Example 2 — Different Structure
$ Input: p = [1,2], q = [1,null,2]
Output: false
💡 Note: Tree p has node 2 as left child of root 1, while tree q has node 2 as right child of root 1. Different structure makes them not identical.
Example 3 — Different Values
$ Input: p = [1,2,1], q = [1,1,2]
Output: false
💡 Note: Same structure but different values: p has left=2, right=1 while q has left=1, right=2. Values don't match at corresponding positions.

Constraints

  • The number of nodes in both trees is in the range [0, 100]
  • -104 ≤ Node.val ≤ 104

Visualization

Tap to expand
Same Tree Problem OverviewTree P: [1,2,3]Tree Q: [1,2,3]123123✓ Same structure: Root→Left,Right✓ Same values: 1==1, 2==2, 3==3Output: true🎯 Key Insight: Trees are same if structure AND values match
Understanding the Visualization
1
Input Trees
Two binary trees p and q to compare
2
Compare Structure & Values
Check if nodes match at all positions
3
Output
Return true if identical, false otherwise
Key Takeaway
🎯 Key Insight: Two trees are identical when they have the same structure and all corresponding nodes have equal values
Asked in
Google 35 Amazon 28 Microsoft 22 Apple 15
312.0K Views
High Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen