← Back to Leo Academy Masterclass

Problem #104: Maximum Depth of Binary Tree

Easy Binary Tree General

Intuition & Strategy Breakdown

Recursively compute maximum depth: 1 + max(maxDepth(root.left), maxDepth(root.right)), returning 0 for null nodes.

Python Solution

def maxDepth(root):
    # Base Case: If node is null, depth is 0
    if not root:
        return 0
    
    # Recursive calls for left and right subtrees
    left = maxDepth(root.left)
    right = maxDepth(root.right)
    
    # Max depth is 1 + max of children
    return 1 + max(left, right)

Java Solution

class Solution {
    public int maxDepth(TreeNode root) {
        if (root == null) return 0;
        return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
    }
}
Watch Interactive Video on Leo Academy Main App