DSA Tracker

Easy

Maximum Depth of Binary Tree

An easy Binary Trees problem included in Apna College, Love Babbar 450, Striver A2Z. Below: the roles whose interviews prioritise this topic, and how to practise it.

Topic
Binary Trees
Sheets
3
Core for
4 roles
Platform
LeetCode

The problem

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

Example 1

Input
[3,9,20,null,null,15,7]
Output
3
Why
The longest path is 3 -> 20 -> 15 or 3 -> 20 -> 7, both with 3 nodes.

Example 2

Input
[1,null,2]
Output
2
Why
The longest path is 1 -> 2 with 2 nodes.

Example 3

Input
[]
Output
0
Why
An empty tree has depth 0.

Constraints

  • The number of nodes is in the range [0, 104].
  • -100 <= Node.val <= 100

How to think about it

Updated 2026-09-09

The depth of any tree is one plus the larger depth of its two subtrees. You do not need to trace or compare whole paths down to individual leaves; depth is an inductive quantity synthesized entirely at the return step of each subproblem.

Approaches, worst first

  1. Level order counting

    time O(n) · space O(w)

    Run breadth-first search using a queue, incrementing a depth counter after exhausting all nodes in each level snapshot. Correct, but allocates a queue that holds the entire tree width in memory.

  2. Postorder bottom-up recursionWrite this one

    time O(n) · space O(h)

    Return 0 for null. For any valid node, compute depths of left and right subtrees recursively and return 1 + max(left, right). It requires no helper data structures and fits in three lines.

Where people lose marks · 3
  • Confusing depth in nodes with depth in edges; a single-node tree has depth 1, while an empty tree has depth 0.
  • In a BFS level-order approach, not snapshotting the queue length before the inner loop causes newly pushed children to merge into the current level.
  • Stack overflow can occur on pathological single-spine trees if recursion is unchecked on deep inputs.

Full solution

Postorder bottom-up recursion: depth is synthesized at the return step from the two subtrees, no queue or explicit stack needed.

Python
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


def max_depth(root: TreeNode | None) -> int:
    if root is None:
        return 0
    # depth of a tree = 1 + the larger depth of its two subtrees
    return 1 + max(max_depth(root.left), max_depth(root.right))
JavaScript
class TreeNode {
  constructor(val = 0, left = null, right = null) {
    this.val = val;
    this.left = left;
    this.right = right;
  }
}

function maxDepth(root) {
  if (root === null) return 0;
  // depth of a tree = 1 + the larger depth of its two subtrees
  return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}
Try it in the editor

The theory behind it

Binary Trees — the ground this problem stands on. All Binary Trees problems

What Binary Trees is

A binary tree is a branching data structure that starts at a single top node called the root, like an upside-down family tree. Every node holds a piece of data and can branch out to at most two children below it, known as the left child and the right child. Because there is no ordering rule about which values go left or right, finding a specific item can require checking every single node in the entire tree.

When to reach for it

Reach for binary trees when problems present hierarchical data with left and right child pointers. Questions asking for tree height, maximum depth, path sums from root to leaf, diameter, lowest common ancestor, or checking whether two trees are mirror reflections of each other all signal binary tree traversals. Any problem asking to inspect or reconstruct a tree layer by layer or path by path belongs here.

How the pattern works

Think recursively by focusing on what a single node must do. If the current node is null, return the base answer immediately. Otherwise, ask the left child for its result, ask the right child for its result, and combine both answers with the current node value before returning up to the parent. For horizontal scans, use a queue to read nodes layer by layer, measuring the queue length at the start of each layer to group nodes by depth.

What each operation costs

OperationTime
traverse all nodes using recursion or queueO(n)
search for an arbitrary value in an unordered treeO(n)
call stack memory on balanced treeO(log n)
call stack memory on skewed treeO(n)
What usually goes wrong with Binary Trees
  • Dereferencing left or right child pointers without checking if the current node is null, throwing null pointer errors on empty trees or leaf nodes.
  • Defining a leaf node incorrectly by stopping when either child is null instead of checking that both left and right children are simultaneously null.
  • Computing tree diameter by taking left height plus right height inside a recursive helper without updating a global maximum across every visited node.

Which roles need this problem

Binary Trees is a core topic for these 4 roles — if you're targeting one of them, this problem is early in your path, not optional.

Secondary for 5 more roles, including Full-Stack Developer, Android Developer, iOS Developer.

Track this in your role's order

Pick your target role and all 370 problems — including this one — resequence to what that interview actually asks. Free.

Start free

More Binary Trees problems

Problem set and role mapping as of .