Maximum Depth of Binary Tree

EasyTreesFree to try
Asked byLinkedInAmazonSpotifyGoogleMicrosoftBloomberg

Problem

Given the root of a binary tree, return its maximum depth — the number of nodes along the longest path from the root down to the farthest leaf.

Examples

Example 1
Input:root = [3,9,20,null,null,15,7]
Output:3
Example 2
Input:root = []
Output:0

Constraints

  • The number of nodes is in the range [0, 10^4].

Try it now — no sign-up needed. Write your solution in Python or JavaScript, run it against test cases, and submit for a verdict, right in your browser.

Open the editor →

How to approach it: the Trees pattern

A tree is a hierarchical structure where each node has at most a fixed number of children (two, for binary trees). Almost every tree problem reduces to a traversal — decide what order you visit nodes in, and what you do at each one.

Look for this pattern when

  • The problem is naturally recursive: "the answer for this tree depends on the answer for its subtrees."
  • You need level-by-level information (BFS) versus depth-first structural information (DFS).

Read the full Trees guide →

Video walkthroughs

Original problem on LeetCode ↗

More Trees problems