Maximum Depth of Binary Tree

Return the maximum depth of the binary tree.

Easy

Examples

Example 1: [3,9,20,null,null,15,7] → 3

Implementation

Ruby


  # --- 2. Maximum Depth of Binary Tree ---
  # Problem: Return the maximum depth of the binary tree.
  # Input: [3,9,20,null,null,15,7]
  # Output: 3
  # Time Complexity: O(n)
  def self.max_depth(root)
    return 0 if root.nil?
    left = max_depth(root.left)
    right = max_depth(root.right)
    [ left, right ].max + 1

Complexity Analysis

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

Patterns & Techniques

Problem Details

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