Introduction
Same Tree means:
- checking whether
- two binary trees
- are completely identical
Conditions:
- structure must match
- node values must match
Example:
Tree 1:
1
/ \
2 3
Tree 2:
1
/ \
2 3
Output:True
Explanation:
Both trees have:
- same structure- same node values
This problem is one of the most important applications of:
DFS Traversal Constraints
1 <= Number of Nodes <= 10^5 Approach : Recursive DFS Solution
Explanations:
Explanation:
The idea is:
- recursively compare nodes
- in both trees simultaneously
Steps:
- Compare current nodes.
- Check node values.
- Recurse left subtree.
- Recurse right subtree.
Conditions:
- both nodes null → valid
- one node null → invalid
- values mismatch → invalid
This approach:
- uses DFS recursion
- compares tree structure and values
Dry Run
Compare:
1 and 1
Values match.
Compare left:
2 and 2
Values match.
Compare right:
3 and 3
Values match.
All nodes matched.Trees are identical.
Practice :