🟩 Same Tree (#100)
🔗 Problem Link
📋 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.
💡 Examples
Example 1
Input: p = [1,2,3], q = [1,2,3]
Output: true
Example 2
Input: p = [1,2], q = [1,null,2]
Output: false
Example 3
Input: p = [1,2,1], q = [1,1,2]
Output: false
🔑 Key Insights & Approach
Core Observation: Recursively check if current nodes match and subtrees match.
Why DFS Recursion?
- Natural recursive structure
- O(n) time, O(h) space
- Clean base cases
Approaches:
- Recursive DFS: O(n) time, O(h) space - optimal
- Iterative BFS: O(n) time, O(n) space
Pattern: "Tree Comparison" recursive pattern.
🐍 Solution: Python
Approach: Recursive DFS
Time Complexity: O(n) | Space Complexity: O(h)
from typing import Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
# Both null
if not p and not q:
return True
# One null, one not
if not p or not q:
return False
# Values don't match
if p.val != q.val:
return False
# Check both subtrees
return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
Approach 2: Iterative BFS
Time Complexity: O(n) | Space Complexity: O(n)
from collections import deque
from typing import Optional
class Solution:
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
queue = deque([(p, q)])
while queue:
node1, node2 = queue.popleft()
if not node1 and not node2:
continue
if not node1 or not node2:
return False
if node1.val != node2.val:
return False
queue.append((node1.left, node2.left))
queue.append((node1.right, node2.right))
return True
🔵 Solution: Golang
Approach: Recursive DFS
Time Complexity: O(n) | Space Complexity: O(h)
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func isSameTree(p *TreeNode, q *TreeNode) bool {
// Both null
if p == nil && q == nil {
return true
}
// One null
if p == nil || q == nil {
return false
}
// Values don't match
if p.Val != q.Val {
return false
}
// Check subtrees
return isSameTree(p.Left, q.Left) && isSameTree(p.Right, q.Right)
}