Same Tree - Problem
Same Tree - Determine if two binary trees are identical
You are given the roots of two binary trees
Two binary trees are considered identical if:
• They have the same structure (same shape and node positions)
• All corresponding nodes have the same values
• Both trees have nodes in the exact same positions
This is a fundamental tree comparison problem that tests your understanding of tree traversal and recursive thinking. The challenge lies in efficiently comparing both structure and values simultaneously.
You are given the roots of two binary trees
p and q. Your task is to write a function that determines whether these two trees are exactly the same.Two binary trees are considered identical if:
• They have the same structure (same shape and node positions)
• All corresponding nodes have the same values
• Both trees have nodes in the exact same positions
This is a fundamental tree comparison problem that tests your understanding of tree traversal and recursive thinking. The challenge lies in efficiently comparing both structure and values simultaneously.
Input & Output
example_1.py — Identical Trees
$
Input:
p = [1,2,3], q = [1,2,3]
›
Output:
true
💡 Note:
Both trees have the same structure and node values: root=1 with left child=2 and right child=3
example_2.py — Different Structure
$
Input:
p = [1,2], q = [1,null,2]
›
Output:
false
💡 Note:
Tree p has node 2 as left child of root, while tree q has node 2 as right child of root - different structures
example_3.py — Different Values
$
Input:
p = [1,2,1], q = [1,1,2]
›
Output:
false
💡 Note:
Trees have same structure but different values: p has left=2,right=1 while q has left=1,right=2
Constraints
- The number of nodes in both trees is in the range [0, 100]
- -104 ≤ Node.val ≤ 104
- Both trees can be empty (null)
Visualization
Tap to expand
Understanding the Visualization
1
Start at Roots
Compare the founding ancestors of both family trees
2
Check Left Branches
Move to the left family line and compare corresponding members
3
Check Right Branches
Move to the right family line and compare corresponding members
4
Recursive Comparison
Continue this process for each sub-family until all branches are checked
Key Takeaway
🎯 Key Insight: By comparing nodes simultaneously during traversal, we achieve optimal performance with early termination when differences are found, avoiding unnecessary computations and extra space for serialization.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code