Start learning free

LESSON 204 OF 314 · BINARY TREES

Maximum Depth of Binary Tree in C++: Recursion in O(n)

Practice O(n) Read the full explanation

You get the root of a binary tree. Return the depth of the tree.

The depth counts the nodes on the longest path from the root down to a leaf. A leaf is a node with no children. An empty tree has a depth of 0.

The trees below are listed level by level, top to bottom and left to right. A missing child is written as NULL.

 

Example 1:

      8
     / \
    4   -2
   /
  5
   \
    1

Input: root = [8,4,-2,5,NULL,NULL,NULL,NULL,1]
Output: 4
Explanation: The longest way down is 8 → 4 → 5 → 1.
It has 4 nodes.
The way to the other leaf, 8 → -2, has only 2 nodes.

Example 2:

Input: root = [6]
Output: 1
Explanation: The root is also the only leaf.

Example 3:

Input: root = []
Output: 0
Explanation: The tree is empty.

 

Constraints:

  • 0 to 10,000 nodes.
  • Each value is from -100 to 100.
  • The tree is at most 400 levels deep.

 

Follow up: Can you find the depth in O(n) time for n nodes? Look at each node just once.
STEP 1 OF 4
    Ctrl + Enter to check

    C++ · BINARY TREES

    Maximum Depth Of Binary Tree in C++, explained

    Problem overview

    The function maxDepth receives the root of a binary tree and returns its maximum depth: the number of nodes on the longest path that starts at the root and goes down to a leaf. An empty tree, whose root is a null pointer, has depth 0.

    The lesson provides the node type in a comment above the class: a TreeNode struct with an int val, two pointers left and right, and one constructor that takes the value and sets both pointers to null.

    For the tree [3,9,20,NULL,NULL,15,7] (level order, NULL for a missing child), the root 3 has a left child 9 and a right child 20, and 20 has children 15 and 7. The paths 3, 20, 15 and 3, 20, 7 have three nodes each, while 3, 9 has two, so the answer is 3. The tree [1,NULL,2] has depth 2, and the empty tree has depth 0.

    Depth here counts nodes, not edges: a tree with a single node has depth 1.

    Approach: one more than the deeper subtree

    A tree is built from smaller trees. The root has a left subtree and a right subtree, and each is a binary tree itself, possibly empty. The longest path from the root goes through the root, then continues down whichever subtree is deeper. So:

    depth(tree) = 1 + max(depth(left subtree), depth(right subtree))
    depth(empty tree) = 0
    

    This is a natural fit for recursion. The function calls itself on the two children and trusts each call to return the right answer for its smaller tree. The empty tree is the base case that ends the recursion: stepping below a leaf reaches a null pointer, which returns 0.

    For [3,9,20,NULL,NULL,15,7], the leaves 9, 15 and 7 each get 1 + max(0, 0) = 1. Node 20 gets 1 + max(1, 1) = 2, and the root gets 1 + max(1, 2) = 3.

    The function visits each node exactly once, which meets the follow-up question's O(n) target.

    Step by step

    1. Handle the empty tree. If root is null, which !root tests, return 0. The same check ends every branch of the recursion, because every path below a leaf runs into a null child.
    2. Find the left depth. Call maxDepth(root->left) and store the result in leftDepth. A missing left child is a null pointer, so it gives 0 by the base case.
    3. Find the right depth the same way, with root->right, into rightDepth.
    4. Combine. Return 1 + max(leftDepth, rightDepth): the root itself, plus the longest path below it.

    The solution in C++

    class Solution {
    public:
        int maxDepth(TreeNode* root) {
            if (!root) {
                return 0;
            }
            int leftDepth = maxDepth(root->left);
            int rightDepth = maxDepth(root->right);
            return 1 + max(leftDepth, rightDepth);
        }
    };
    

    The C++ details worth a closer look:

    • Null checks. !root is true when the pointer is null. Without the check, root->left on a null pointer is undefined behaviour and usually crashes the program.
    • max. max(leftDepth, rightDepth) comes from <algorithm> and needs two arguments of the same type, here two ints.
    • Pointer, not copy. TreeNode* is passed by value, but a pointer is a small address, so passing it costs nothing, and the function only reads the tree. It doesn't change any node.
    • Stack depth. Each recursive call uses a stack frame. The recursion goes as deep as the tree, which the constraints cap at 400 levels, so there's no risk of overflowing the stack. A tree that could degenerate into a chain of 100,000 nodes would need an iterative version, such as a breadth-first search that counts levels.

    Complexity

    Let n be the number of nodes and h the height of the tree.

    Time: O(n). Each node is visited once. It does a constant amount of work, and every null child costs one extra call that returns immediately. A tree with n nodes has n + 1 null children, so the total number of calls is 2n + 1.

    Space: O(h). The only extra memory is the recursion stack, which holds one frame per level on the current path. That is O(log n) for a balanced tree and O(n) for a chain.

    Edge cases and common mistakes

    • Empty tree. A null root returns 0, as the third example expects.
    • Single node. Both children are null, so the result is 1 + max(0, 0) = 1.
    • A chain. [1,NULL,2] returns 2, and a tree where every node has only a left child works the same way: the missing side contributes 0 and the other side decides.
    • Lopsided trees. [1,2,NULL,3,NULL,4] is a chain of four nodes going left, and its depth is 4. The right side is empty at every level and never wins the max.
    • Counting edges instead of nodes. The lesson counts nodes, so a leaf has depth 1. Returning -1 for the empty tree, the edge-counting convention, would give answers one too small.
    • Forgetting the 1 +. The function would return 0 for every tree, since only null pointers ever return a number.
    • Using min. That finds the shallowest leaf path, not the deepest. It also goes wrong when one child is missing, since the empty side returns 0.

    Testing

    • [3,9,20,NULL,NULL,15,7] gives 3.
    • [1,NULL,2] gives 2.
    • [] gives 0.
    • [5] gives 1.
    • [1,2,NULL,3,NULL,4] gives 4.
    • A chain of 400 nodes, each the left child of the one before, gives 400.
    Keep going with C++1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free