Taro Logo

Maximum Depth of Binary Tree

#207 Most AskedEasy
Topics:
TreesRecursion

Given the root of a binary tree, return its maximum depth.

A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Example 1:

Input: root = [3,9,20,null,null,15,7]
Output: 3

Example 2:

Input: root = [1,null,2]
Output: 2

Constraints:

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

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Can the tree be empty (i.e., is the root node allowed to be null), and if so, should the depth be considered 0?
  2. What is the maximum expected number of nodes (or maximum height) in the binary tree, and should I be concerned about call stack overflow from recursion limits?
  3. Are the node values constrained to standard integers, and could the tree be unbalanced or skewed in a way that approaches a linked list?
  4. Is the definition of a "leaf node" strictly a node with no left and no right children?
  5. Should the depth be measured as the number of nodes along the longest path, or the number of edges?

Brute Force Solution

Approach

Imagine you are holding an upside-down family tree where every person branches out into more family members. To find the longest path from the top ancestor down to the very last descendant, the brute force strategy checks every single possible path through the entire family tree.

Here's how the algorithm would work step-by-step:

  1. Start at the very top person of the tree.
  2. Look at all the branches going downward and pick one path to follow.
  3. Walk all the way down that path until you reach a person who has no more descendants below them.
  4. Count how many steps or people you passed through on that specific journey.
  5. Remember that number as the longest path you have found so far.
  6. Go back up to the top and choose a completely different path that you have not fully explored yet.
  7. Walk all the way down that new path, count the steps, and compare it to your previous best count, updating your record if this new path is longer.
  8. Repeat this exhaustive process for every single possible path from the top to the bottom of the tree.
  9. Once you have checked every single path, the final recorded number is your answer.

Code Implementation

class Solution:
    def maxDepth(self, root_node):
        if not root_node:
            return 0
        
        # We maintain a stack to explore every single path down to the leaves independently
        path_stack = [(root_node, 1)]
        maximum_depth_found = 0
        
        while path_stack:
            current_node, current_depth = path_stack.pop()
            
            if current_node:
                maximum_depth_found = max(maximum_depth_found, current_depth)
                
                # We push both children to explore all branches exhaustively
                path_stack.append((current_node.left, current_depth + 1))
                path_stack.append((current_node.right, current_depth + 1))
                
        return maximum_depth_found

Big(O) Analysis

Time Complexity
O(2ⁿ) – To find the maximum depth by exploring every single possible path through the entire family tree, the brute force strategy repeatedly traverses branches down to every leaf node. For a binary tree where each node branches into two descendants, checking all potential paths results in roughly 2ⁿ operations in the worst-case scenario. Summing the steps required to exhaustively check these paths across all nodes leads to a total operational count proportional to 2ⁿ, which simplifies to an exponential time complexity of O(2ⁿ).
Space Complexity
O(h) – The space complexity is driven entirely by the recursion stack frames required to walk down the paths of the tree. In the worst-case scenario where the tree is completely linear, the algorithm visits every node sequentially, resulting in a maximum call stack depth equal to the total number of nodes N. For a balanced tree, this depth shrinks to the height of the tree, which is proportional to log N. Therefore, the auxiliary space complexity scales with the maximum depth of the tree.

Optimal Solution

Approach

To find the maximum depth of a family tree represented as connected branches, we can break the problem down by looking at smaller sub-branches. We ask each branch to report the length of its longest path downward, and we use that information to find the absolute deepest path.

Here's how the algorithm would work step-by-step:

  1. Begin at the very top person or starting point of the structure.
  2. Check if there are any branches extending downward from your current position. If there are no branches at all, report a depth of zero for this point.
  3. If there are branches extending downward, visit each branch and ask it to report its own depth.
  4. Compare the answers you get back from the downward branches and pick the one that goes down the furthest.
  5. Add one to that maximum depth to account for the step you just took to get to your current position.
  6. Pass this final calculated depth upward so the previous level can use it in its own comparison.

Code Implementation

def max_depth(tree_node):
    # Base case returns zero when the branch terminates without further children.
    if tree_node is None:
        return 0

    left_branch_depth = max_depth(tree_node.left)

    right_branch_depth = max_depth(tree_node.right)

    # We add one to include the current node in the overall depth calculation.
    return max(left_branch_depth, right_branch_depth) + 1

Big(O) Analysis

Time Complexity
O(n) – The time complexity is driven by the recursive traversal of the tree, where n represents the total number of nodes in the binary tree. Starting from the top, the algorithm visits every single node and every single branch exactly once to ask for its depth. As we compute the maximum depth for each node, the work done per node is constant. This results in visiting n nodes directly, approximating a linear operation count of 1 * n steps, which simplifies to O(n).
Space Complexity
O(H) – The space complexity is driven entirely by the recursion stack frames implied when visiting each downward branch recursively. In the worst-case scenario of a completely unbalanced tree, the depth reaches N, requiring stack frames proportional to the input size N. For a completely balanced tree, the maximum depth of the recursion stack is proportional to log(N). Therefore, the auxiliary space complexity simplifies to O(H) where H represents the height of the binary tree.

Edge Cases

Null root pointer representing an empty tree
How to Handle:
The base case checks for a null node and immediately returns a depth of 0.
A single-node binary tree with no children
How to Handle:
Both recursive calls return 0, and the function correctly evaluates 1 plus the maximum of those zeros to return 1.
A severely skewed tree resembling a linked list
How to Handle:
Recursive DFS solutions will risk a stack overflow if the depth exceeds the call stack limit, requiring an iterative BFS approach for massive inputs.
A completely balanced binary tree of maximum constraints
How to Handle:
The depth is logarithmic relative to the number of nodes, easily fitting well within standard recursion limits.
Nodes containing negative values, zeros, or extreme integer boundaries
How to Handle:
Since the algorithm only tracks path length by counting node instances rather than evaluating node values, these values have no impact on the calculation.
Unbalanced trees where left and right subtrees have vastly different heights
How to Handle:
The max function properly evaluates both branches and selects the greater depth to ensure the longest path is measured.
0/245 completed