Maximum depth of Binary Tree


Maximum Depth of Binary Tree – LeetCode


Problem: Maximum Depth of Binary Tree

Problem Statement

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

The maximum depth of a binary tree is the number of nodes along the longest path from the root node down to the farthest leaf node.


Examples

Example 1

Input:

     3
    / \
   9  20
      / \
     15  7

Output: 3

Example 2

Input:

root = [1,null,2]

Output: 2


Constraints


Intuition

To compute the maximum depth of a binary tree, we can break the problem into:

This is a classical application of recursion.


Approach (Recursion using Induction – Base Case – Hypothesis)

1. Base Case:

If the node is null, return 0 (depth of empty tree is 0)

2. Hypothesis:

Assume that maxDepth(root.left) and maxDepth(root.right) give correct depth of left and right subtree.

3. Induction:

Return 1 + max(leftDepth, rightDepth) as the final answer.


Code (Java)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */

class Solution {
    public int maxDepth(TreeNode root) {
        // Base case
        if (root == null) return 0;

        // Hypothesis
        int leftDepth = maxDepth(root.left);
        int rightDepth = maxDepth(root.right);

        // Induction
        return 1 + Math.max(leftDepth, rightDepth);
    }
}

Time and Space Complexity


Dry Run

Input:

       1
        \
         2
          \
           3

Call stack:


Conclusion

This problem highlights how to reduce a problem to its substructure using recursion.
It's a perfect case for divide and conquer, and reinforces the idea of thinking recursively in trees.