Start learning free

LESSON 204 OF 314 · BINARY TREES

Maximum Depth of Binary Tree in C#: Recursion, 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 method MaxDepth receives the root of a binary tree and returns its maximum depth: the number of nodes on the longest path from the root down to a leaf. An empty tree, where root is null, has depth 0.

    The lesson provides the TreeNode class. A node has an int val and two TreeNode fields, left and right, which are null when the child is missing. A TreeNode is created with new TreeNode(x).

    For the tree [3,9,20,null,null,15,7], listed level by level, the root 3 has children 9 and 20, and 20 has children 15 and 7. The paths 3, 20, 15 and 3, 20, 7 have three nodes, and 3, 9 has two, so the answer is 3. For [1,null,2] the answer is 2, and for an empty tree it is 0. Counting nodes rather than edges is the point to remember: a single node has depth 1.

    Approach: one more than the deeper subtree

    A tree is built from smaller trees, and its depth follows the same pattern. The longest path from the root goes down through either the left child or the right child, so the depth of a tree is one (for the root) plus the larger of the depths of its two subtrees.

    That sentence is already a recursive algorithm. To find the depth of a tree, find the depth of the left subtree, find the depth of the right subtree, and combine them. You don't need to follow what happens inside the recursive calls: trust that each call returns the right depth for the smaller tree it receives.

    The recursion needs a base case, and the natural one is the empty tree: its depth is 0. This single check also handles every missing child. A leaf has two null children, so both recursive calls return 0, and the leaf's own depth is 1 + max(0, 0), which is 1.

    Each node is visited exactly once, so the method runs in O(n) time for a tree of n nodes. Depth could also be found level by level with a queue, but the recursive version is shorter.

    Running the method on a few trees gives these depths: [3,9,20,null,null,15,7] gives 3, [1,null,2] gives 2, an empty tree gives 0, a single node [5] gives 1, and a chain of four nodes that keeps going left, [1,2,null,3,null,4], gives 4.

    Step by step

    1. Write the base case. If root == null, return 0. An empty tree has no nodes. This check also stops the recursion when it steps past a leaf.
    2. Find the left depth. Call MaxDepth(root.left) and store the result in an int named leftDepth. The call returns the depth of whatever tree hangs under the left child.
    3. Find the right depth the same way with root.right, and store it in rightDepth. A missing child simply gives 0, thanks to the base case.
    4. Combine them. Return 1 + Math.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 == null) {
                return 0;
            }
            int leftDepth = MaxDepth(root.left);
            int rightDepth = MaxDepth(root.right);
            return 1 + Math.Max(leftDepth, rightDepth);
        }
    }
    

    The C# details worth knowing:

    • Class instances are references. TreeNode is a class, so a TreeNode variable holds a reference that can be null. That is why root == null is a valid test, and why a missing child is just a null field.
    • Field names are lowercase here. The lesson's TreeNode uses val, left and right, while the method is MaxDepth. Method names in C# are PascalCase by convention, but the tree's fields follow the names the lesson provides. Use them exactly: root.Left would not compile.
    • Math.Max is in System. It takes two numbers of the same type and returns the larger one.
    • A method can call itself. No special syntax is needed. Each call gets its own root, leftDepth and rightDepth.
    • Recursion depth is the tree's height. The lesson's trees are at most 400 levels deep, which is far below the limit of the call stack. A degenerate chain of 10,000 nodes, all left children, also returns 10000 without trouble, but a much longer chain could overflow the stack, which ends the program.

    Complexity

    Time: O(n). Every node causes one call that does constant work, plus one call for each missing child that returns at once. That is at most about 2n + 1 calls.

    Space: O(h), where h is the height of the tree, for the call stack. For a balanced tree that is about log n. For a chain where every node has one child, it is n. The method allocates nothing else.

    Edge cases and common mistakes

    • Empty tree. null returns 0.
    • A single node. It returns 1: both children are missing, so the answer is 1 + Math.Max(0, 0).
    • A chain. A tree where each node has only a right child, such as [1,null,2], returns its length, 2. A missing left child doesn't make the tree shallower.
    • Counting edges instead of nodes. The depth here is the number of nodes on the path. Returning 0 for the base case and 0 for a leaf would give one less than the expected answer.
    • Using + instead of Math.Max. Adding the two depths counts both subtrees, which isn't a path from the root to a leaf.
    • Forgetting the base case. Without it the recursion would call MaxDepth on null and then read null.left, which throws NullReferenceException.

    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 10,000 left children gives 10000.
    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