Check if two binary trees are the same.
p = [1,2,3], q = [1,2,3] → true
# --- 3. Same Tree ---
# Problem: Check if two binary trees are the same.
# Input: p = [1,2,3], q = [1,2,3]
# Output: true
# Time Complexity: O(n)
def self.is_same_tree(p, q)
return true if p.nil? && q.nil?
return false if p.nil? || q.nil?
return false unless p.val == q.val
is_same_tree(p.left, q.left) && is_same_tree(p.right, q.right)
O(n)
O(h)