104. Maximum Depth of Binary Tree

easy trees

Find the maximum depth of a binary tree.

Given the root of a binary tree, return its maximum depth.

Approach

Recursive DFS: depth = 1 + max(left, right) — O(n) time, O(h) space where h is tree height.

Solutions

Ruby

def max_depth(root)
  return 0 if root.nil?
  1 + [max_depth(root.left), max_depth(root.right)].max
end

Python

def max_depth(root: TreeNode | None) -> int:
    if not root:
        return 0
    return 1 + max(max_depth(root.left), max_depth(root.right))

Go

func maxDepth(root *TreeNode) int {
    if root == nil {
        return 0
    }
    left := maxDepth(root.Left)
    right := maxDepth(root.Right)
    return 1 + max(left, right)
}

func max(a, b int) int {
    if a > b { return a }
    return b
}

TypeScript

function maxDepth(root: TreeNode | null): number {
    if (!root) return 0;
    return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}

Elixir

defmodule Solution do
  def max_depth(nil), do: 0
  def max_depth(%{left: left, right: right}) do
    1 + max(max_depth(left), max_depth(right))
  end
end