Maximum Depth of Binary Tree

easyTrees: Traversal48 stepsJava · Python · C++

The depth of a tree is 1 (for the root) plus the deeper of its two subtrees. An empty tree has depth 0. Recursion computes it bottom-up: each node waits for its children's depths.

▶ Watch the animated trace

Traced input: root = [3, 9, 20, null, null, 15, 7] → 3. Original problem: neetcode.io/problems/depth-of-binary-tree

Complexity

BestO(n)
AverageO(n)
WorstO(n)
SpaceO(h)

Every node is visited once; the call stack is as deep as the tree (h), O(n) for a skewed tree.

Key idea

Common mistakes

Solution

Java
int maxDepth(TreeNode root) {
    if (root == null) return 0;
    int left = maxDepth(root.left);
    int right = maxDepth(root.right);
    int depth = 1 + Math.max(left, right);
    return depth;
}
Python
def maxDepth(root: Optional[TreeNode]) -> int:
    if not root: return 0
    left = maxDepth(root.left)
    right = maxDepth(root.right)
    return 1 + max(left, right)
C++
int maxDepth(TreeNode* root) {
    if (!root) return 0;
    int left = maxDepth(root->left);
    int right = maxDepth(root->right);
    return 1 + max(left, right);
}

Edge cases

Each one has its own trace in the interactive view.

CaseInputAnswer
Empty tree
The base case returns immediately.
root = []0
Single node
Both children return 0.
root = [1]1
Skewed tree
A chain: the recursion is as deep as the number of nodes.
root = [1, 2, null, 3, null, 4]4
Unbalanced
Only the right subtree adds depth.
root = [1, null, 2]2
← Merge k Sorted ListsInvert Binary Tree →