Same Tree - Problem
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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code