Data Structures & Algorithms Binary Trees
💡
Exercise 90

Same Tree 15 XP Easy

LeetCode Ctrl+Enter Run Ctrl+S Save

Given two binary trees, determine if they are structurally identical and have the same node values.

# Tree 1: 1 Tree 2: 1 # / \ / \ # 2 3 2 3 # → True (same structure, same values) # Tree 1: 1 Tree 2: 1 # / \ # 2 2 # → False (different structure)

Recursive comparison:

  • If both nodes are None → same (both empty)
  • If one is None and other isn't → different
  • If values differ → different
  • Otherwise: recursively check left subtrees AND right subtrees
📋 Instructions
Implement `is_same_tree(p, q)` that returns True if two trees are identical. Test with identical and different trees.
Base: if not p and not q, return True. If not p or not q, return False. If p.val != q.val, return False. Return is_same_tree(p.left, q.left) and is_same_tree(p.right, q.right).
🧪 Test Cases
Input
is_same_tree(t1, t2)
Expected
True
Boolean check
Input
is_same_tree(t1, t3)
Expected
False
Boolean check
Input
is_same_tree(None, None)
Expected
True
Edge case — null/empty input
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.