Trees · Coding problem

Maximum Depth of Binary Tree

A free coding problem from the Binary Tree Traversal skill. Read it here, then solve it in the app in Java or Python.

  • Easy
  • Coding problem
  • Free
  • Java and Python

The problem

How deep does a binary tree go? Count the nodes on the longest path from the root down to a leaf, root and leaf included.

Input format (this platform's convention, not LeetCode's)

The tree is given as a flat, 0-indexed array where the node at index i has its left child at index 2*i + 1 and its right child at index 2*i + 2. The literal token null marks a missing node (and every index at or beyond the array's length is also treated as missing). This is the same "heap array" layout used for binary heaps, and it keeps the tree-building logic unambiguous regardless of shape.

Example

Input:  [8, 3, 10, 1, 6, null, 14, null, null, 4]
Output: 4

The tree looks like this, and the longest path is 8 -> 3 -> 6 -> 4:

        8
      /   \
     3     10
    / \      \
   1   6      14
      /
     4

Constraints

  • 0 <= number of array tokens <= 2000
  • -10^4 <= node value <= 10^4

How it's graded

  • Run checks your code against the examples. Submit also runs a hidden suite in four groups - basic cases, edge cases, random inputs and performance tests at the size limit - and shows which groups pass, never the hidden inputs.
  • Stuck? Hints come in four steps, from a nudge to a code skeleton, each costing part of the points.
  • Once you pass, you see the approaches from brute force to optimal, and where your solution lands among them.

More problems in Binary Tree Traversal

Solve it Maximum Depth of Binary Tree free

No card needed. Lessons, practice questions and easy problems are free forever.

Free plan, no card · 7-day Pro trial · Cancel anytime