Maximum Depth of Binary Tree in Java: Explanation & Practice

Find the maximum depth (height) of a binary tree

Problem summary

Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from root to a leaf.

Starter code

public class Main {
    public static void main(String[] args) {
        // Tree:     3
        //          / \
        //         9  20
        //            / \
        //           15  7
        // Print: Depth: 3
    }
}

Expected output and test cases

  • [3,9,20,null,null,15,7]
    Depth: 3
  • [1,null,2]
    Depth: 2
  • [] → 0
    Depth: 0

Hints

  1. Base case: null node has depth 0
  2. Recursive: 1 + max(depth(left), depth(right))
  3. Can also use BFS level-by-level counting
  4. Each recursion adds 1 to the depth

Related Data Structures & Algorithms exercises

Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler