Skip to content

Same Tree

Given the roots of two binary trees p and q, write a function to check if they are the same.

Two binary trees are considered the same if they are structurally identical and the nodes have the same values.

pqOutputExplanation
[1,2,3][1,2,3]trueTrees are identical in structure and values
[1,2][1,null,2]falseDifferent structure (left vs. right child)
[1,2,1][1,1,2]falseSame structure but different values at positions
  • The number of nodes in each tree is in the range [0, 100].
  • -10^4 <= Node.val <= 10^4
ApproachTimeSpaceBest When
DFS RecursiveO(min(m, n))O(min(h1, h2))Small trees; clean recursive code preferred
BFS Level-OrderO(min(m, n))O(min(w1, w2))Wide, shallow trees; iterative approach preferred

m and n = number of nodes; h = height; w = max width at any level

  • Learn DFS Recursive first — it is elegant, concise, and mirrors the recursive tree structure naturally.
  • Use BFS as a variation if you want to practice iterative techniques or need explicit level-order thinking.
Elegant & Intuitive
DFS Recursive
O(min(m, n)) time · O(min(h1, h2)) space
Iterative Alternative
BFS Level-Order
O(min(m, n)) time · O(min(w1, w2)) space
★ Recommended

Compare nodes recursively by checking:

  1. Are both nodes null? (equal)
  2. Is exactly one null? (not equal)
  3. Do values differ? (not equal)
  4. Recursively check left and right subtrees

This mirrors the natural recursive structure of trees and reaches all nodes in minimal time.

⏱ Time O(min(m, n)) Each node visited at most once 💾 Space O(min(h1, h2)) Call stack depth = tree height

Input: p = [1,2,3], q = [1,2,3]

1 1
/ \ / \
2 3 2 3
StepCheckResult
Compare rootsp.val == q.val (1 == 1)Continue
Left subtreeisSameTree(p.left=2, q.left=2)true
Right subtreeisSameTree(p.right=3, q.right=3)true
ResultBoth children matchtrue

Animated walkthrough

How DFS recursion compares trees node-by-node

Use Next or Autoplay to see the algorithm recursively traverse and compare both trees simultaneously.

Step 1 of 4
Waiting to begin...
Array state
Memory / lookup state

function isSameTree(p, q):
if p is null and q is null:
return true
if p is null or q is null:
return false
if p.val != q.val:
return false
return isSameTree(p.left, q.left) and isSameTree(p.right, q.right)
same_tree_dfs.py
from typing import Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def isSameTree(p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
"""
Check if two binary trees are the same using DFS (recursive).
Time Complexity: O(min(m, n)) where m and n are the number of nodes in each tree
Space Complexity: O(min(h1, h2)) where h1 and h2 are the heights of the trees (call stack)
"""
# Both nodes are None (base case: equal)
if p is None and q is None:
return True
# One is None, the other isn't (not equal)
if p is None or q is None:
return False
# Values differ (not equal)
if p.val != q.val:
return False
# Recursively check left and right subtrees
return isSameTree(p.left, q.left) and isSameTree(p.right, q.right)
# Test cases
if __name__ == "__main__":
# Example 1: Same trees
# 1 1
# / \ / \
# 2 3 2 3
p1 = TreeNode(1)
p1.left = TreeNode(2)
p1.right = TreeNode(3)
q1 = TreeNode(1)
q1.left = TreeNode(2)
q1.right = TreeNode(3)
print(isSameTree(p1, q1)) # Expected: True
# Example 2: Different structure
# 1 1
# / \
# 2 2
p2 = TreeNode(1)
p2.left = TreeNode(2)
q2 = TreeNode(1)
q2.right = TreeNode(2)
print(isSameTree(p2, q2)) # Expected: False
# Example 3: Different values
# 1 1
# / \ / \
# 2 1 1 2
p3 = TreeNode(1)
p3.left = TreeNode(2)
p3.right = TreeNode(1)
q3 = TreeNode(1)
q3.left = TreeNode(1)
q3.right = TreeNode(2)
print(isSameTree(p3, q3)) # Expected: False
# Example 4: Both empty
p4 = None
q4 = None
print(isSameTree(p4, q4)) # Expected: True
alternative

Use a queue to store pairs of nodes from both trees. At each step, dequeue a pair, check if they match, and enqueue the children. This allows you to compare the trees level-by-level (breadth-first) instead of depth-first.

⏱ Time O(min(m, n)) Each node visited once 💾 Space O(min(w1, w2)) Queue holds at most max width nodes

Input: p = [1,2,3], q = [1,2,3]

Queue StateCheckEnqueueStatus
[(1,1)]1 == 1(2,2), (3,3)Match
[(2,2), (3,3)]2 == 2(null,null), (null,null)Match
[(null,null), (3,3)]Both nullSkip
[(3,3)]3 == 3(null,null), (null,null)Match
[(null,null), (null,null)]Both nullSkip
[]All comparedtrue
function isSameTree(p, q):
queue = [(p, q)]
while queue is not empty:
node1, node2 = queue.dequeue()
if node1 is null and node2 is null:
continue
if node1 is null or node2 is null or node1.val != node2.val:
return false
queue.enqueue((node1.left, node2.left))
queue.enqueue((node1.right, node2.right))
return true
same_tree_bfs.py
from typing import Optional
from collections import deque
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def isSameTree(p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
"""
Check if two binary trees are the same using BFS (level-order traversal).
Time Complexity: O(min(m, n)) where m and n are the number of nodes in each tree
Space Complexity: O(min(w1, w2)) where w1 and w2 are the widths of the trees
"""
# Use a queue to store pairs of nodes to compare
queue = deque([(p, q)])
while queue:
node1, node2 = queue.popleft()
# Both are None (equal)
if node1 is None and node2 is None:
continue
# One is None or values differ (not equal)
if node1 is None or node2 is None or node1.val != node2.val:
return False
# Add children to queue for comparison
queue.append((node1.left, node2.left))
queue.append((node1.right, node2.right))
return True
# Test cases
if __name__ == "__main__":
# Example 1: Same trees
# 1 1
# / \ / \
# 2 3 2 3
p1 = TreeNode(1)
p1.left = TreeNode(2)
p1.right = TreeNode(3)
q1 = TreeNode(1)
q1.left = TreeNode(2)
q1.right = TreeNode(3)
print(isSameTree(p1, q1)) # Expected: True
# Example 2: Different structure
# 1 1
# / \
# 2 2
p2 = TreeNode(1)
p2.left = TreeNode(2)
q2 = TreeNode(1)
q2.right = TreeNode(2)
print(isSameTree(p2, q2)) # Expected: False
# Example 3: Different values
# 1 1
# / \ / \
# 2 1 1 2
p3 = TreeNode(1)
p3.left = TreeNode(2)
p3.right = TreeNode(1)
q3 = TreeNode(1)
q3.left = TreeNode(1)
q3.right = TreeNode(2)
print(isSameTree(p3, q3)) # Expected: False
# Example 4: Both empty
p4 = None
q4 = None
print(isSameTree(p4, q4)) # Expected: True