Same Tree
Problem Statement:β
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.
Example 1:

Input: p = [1,2,3], q = [1,2,3]
Output: true
-
Example:
β Solution: Recursive Tree Comparisonβ
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
// Both trees are empty
if(p == NULL && q == NULL) return true;
// One of the trees is empty
if(p == NULL || q == NULL) return false;
// Values must be equal, and both subtrees must match
return (p->val == q->val) &&
isSameTree(p->left, q->left) &&
isSameTree(p->right, q->right);
}
};
π How It Worksβ
- This is a simple DFS-based recursion.
- The function compares:
- Structure: both left and right children must be present/missing together.
- Values: corresponding nodes must hold the same value.
- Recursion continues until all nodes are matched or a mismatch is found.
π§© Key Logicβ
if(p == NULL && q == NULL) return true; // both empty
if(p == NULL || q == NULL) return false; // structure mismatch
if(p->val != q->val) return false; // value mismatch
Then continue recursively on left and right subtrees.
β±οΈ Time & Space Complexityβ
| Metric | Value |
|---|---|
| β±οΈ Time Complexity | O(n), where n = number of nodes (min of both trees) |
| πͺ Space Complexity | O(h), where h = height of tree (due to recursion stack) |
β οΈ Edge Casesβ
- β
Both trees empty β return
true - β
One tree empty β return
false - β
Values same but structure different β return
false - β
Values and structure same β return
true
π‘ Other Approachesβ
| Approach | Notes |
|---|---|
| Iterative using stack/queue | Possible, but more verbose |
| BFS level-order comparison | Also valid, but recursion is cleaner and preferred |
π Related Problemsβ
- LeetCode 100. Same Tree
- LeetCode 572. Subtree of Another Tree
- LeetCode 101. Symmetric Tree
- LeetCode 226. Invert Binary Tree
π¬