Same Tree

Check if two binary trees are the same.

Easy

Examples

Example 1: p = [1,2,3], q = [1,2,3] → true

Implementation

Ruby

  # --- 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)

Complexity Analysis

Time Complexity: O(n)
Space Complexity: O(h)

Patterns & Techniques

Problem Details

Category: Trees And Recursion
Difficulty: Easy
Module: TreesAndRecursion
Method: self.is_same_tree
← Back to Trees And Recursion