Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources
Maximum Depth of Binary Tree

Maximum Depth of Binary Tree

Problem Statement

You’re a tree climber measuring the height of a binary tree from root to deepest leaf. Return the maximum depth. This easy-level recursive gem is a vertical voyage—dive deep with DFS or BFS to find the bottom!

Example

Input: root = [3,9,20,null,null,15,7]

Tree:

   3
  / \
 9  20
   /  \
  15   7

Output: 3 (Root to 15 or 7)

Input: root = [1,null,2]

Output: 2

Input: root = []

Output: 0

Code

Java
Python
JavaScript
class Solution {
    public int maxDepth(TreeNode root) {
        if (root == null) return 0;
        return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
    }
}
            
class Solution:
    def maxDepth(self, root):
        if not root:
            return 0
        return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
            
function maxDepth(root) {
    if (!root) return 0;
    return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}
            

Explanation

  • DFS Insight: Depth = 1 + max of left and right subtree depths.
  • Flow: Recursively compute depth for each subtree, take the larger, add 1 for current level.
  • Example Walkthrough: [3,9,20,null,null,15,7] → 9=1, 15=1, 7=1, 20=2, 3=3.
  • BFS Alt: Use queue, count levels—same result, different style.
  • Edge Cases: Null root, single node, unbalanced tree—all covered.

Note

Time complexity: O(n), Space complexity: O(h) for recursion stack. A depth-diving delight—simple yet profound!