Start learning free

LESSON 487 OF 673 · BINARY TREES

Maximum Depth of Binary Tree in Python: 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 None.

 

Example 1:

      8
     / \
    4   -2
   /
  5
   \
    1

Input: root = [8,4,-2,5,None,None,None,None,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

    PYTHON · BINARY TREES

    Maximum Depth Of Binary Tree in Python, 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 None, has depth 0.

    The lesson provides the TreeNode class, where each node has val, left and right, and a missing child is None. Trees are written in level order, top to bottom and left to right, with None for a missing child.

    For [3, 9, 20, None, None, 15, 7] 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 each, and 3, 9 has two, so the answer is 3. For [1, None, 2] the only path is 1, 2, so the answer is 2. For [] the answer is 0.

    Approach: one more than the deeper subtree

    A tree is built from smaller trees: a root with a left subtree and a right subtree. Any longest path starts at the root and then goes down into one of the two subtrees. It goes into the deeper one, so:

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

    The 1 is the root itself. The subtrees are trees too, so the same rule applies to them, which is recursion. It needs a base case, an empty tree, which has depth 0. That also covers the missing children of leaves: a leaf has two empty subtrees, so its depth is 1 + max(0, 0) = 1.

    Each node is visited exactly once, so the running time is O(n) for n nodes. The follow-up of the problem asks for this.

    Step by step

    1. Handle the empty tree. If not root is true, root is None: return 0. This also stops the recursion after it steps past a leaf.
    2. Find the left depth. Call self.maxDepth(root.left) and store the result in leftDepth. Trust the call to return the right answer for the smaller tree, whatever its shape.
    3. Find the right depth the same way, with root.right, and store it in rightDepth. A missing child gives 0.
    4. Combine them. Return 1 + max(leftDepth, rightDepth): the root plus the longest path below it.

    The solution in Python

    class Solution:
        def maxDepth(self, root: Optional[TreeNode]) -> int:
            if not root:
                return 0
            leftDepth = self.maxDepth(root.left)
            rightDepth = self.maxDepth(root.right)
            return 1 + max(leftDepth, rightDepth)
    

    Python details worth a closer look:

    • not root. A TreeNode object is always truthy and None is falsy, so if not root is true exactly for an empty tree. A node whose val is 0 is still truthy, because the test is on the node and not on its value.
    • Optional[TreeNode]. This annotation says the argument is either a TreeNode or None. Python doesn't enforce it, so it documents the base case more than it checks anything.
    • Calling the method recursively. The recursive call goes through self, as in self.maxDepth(root.left). Writing maxDepth(root.left) on its own raises NameError, because inside a method the name isn't in scope.
    • The recursion limit. Python allows about 1,000 nested calls by default. The tree here is at most 400 levels deep, so the recursion stays well within the limit. A chain of 2,001 nodes would raise RecursionError with this solution.

    Complexity

    Time: O(n). Each node is visited once. A node does a constant amount of work besides the two recursive calls: a check, an addition and a comparison. The calls on missing children return immediately, and there are at most n + 1 of them.

    Space: O(h), where h is the height of the tree. The call stack holds one frame per level of the path being explored. For a balanced tree that is about log n. For a tree where every node has one child it is n, and the constraint of 400 levels keeps it small here.

    Edge cases and common mistakes

    • Empty tree. [] gives 0. Without the base case, the function would try root.left on None and raise AttributeError.
    • Single node. [1] gives 1: both children are missing, so the result is 1 + max(0, 0).
    • A tree that is a single chain. [1, 2, None, 3] has the path 1, 2, 3 going left, so the answer is 3. The right side is empty at every level, and the maximum picks the left.
    • Counting edges instead of nodes. The depth here counts nodes. The path 3, 20, 15 has 3 nodes and 2 edges, and the expected answer is 3. A base case of -1 would give edge counts.
    • Using min instead of max. For [1, None, 2] it would return 1, as the empty left side would win. The longest path is wanted, not the shortest.
    • Forgetting the 1 +. Without it the function returns 0 for every tree, because only the base case ever produces a number.
    • Adding the two depths. leftDepth + rightDepth measures a path that goes down one side and up the other, not the depth from the root.

    Testing

    • [3, 9, 20, None, None, 15, 7] gives 3.
    • [1, None, 2] gives 2.
    • [] gives 0.
    • [1] gives 1.
    • [1, 2, None, 3] gives 3.
    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free