Article start
DSA Course: Interview Patterns and Problem Solving
Module 6: Trees

Maximum Depth of Binary Tree: Height recursion Pattern

Compute the longest root-to-leaf depth using recursive height logic.

May 29, 2026·21

Learning Outcome

After this lesson, you should be able to define tree height recursively and return the maximum depth from the root.

Problem Statement

Given the root of a binary tree, return its maximum depth. The maximum depth is the number of nodes on the longest path from the root to a leaf.

InputOutputWhy
[3,9,20,null,null,15,7]3The longest root-to-leaf path has 3 nodes.

Brute Force Approach

Store every root-to-leaf path, then return the length of the longest path.

This works but stores unnecessary path lists. The depth can be computed directly.

Optimized Approach

For any node, the maximum depth is 1 + max(depth(left), depth(right)). A null node contributes depth 0.

Exact Pseudocode

maxDepth(node):
  if node is null:
    return 0
  leftDepth = maxDepth(node.left)
  rightDepth = maxDepth(node.right)
  return 1 + max(leftDepth, rightDepth)

Reference Code

class Solution:
    def maxDepth(self, root):
        if not root:
            return 0
        return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))

Sample Dry Run

NodeleftDepthrightDepthReturn
9001
15001
7001
20112
3123

Complexity

MeasureValueReason
TimeO(n)Each node contributes once.
SpaceO(h)The recursion stack depends on height.

Edge Cases

  • Empty tree returns 0.
  • Single-node tree returns 1.
  • Skewed tree has height n.

Interview Checklist

  • Use 0 for null depth.
  • Add 1 for the current node.
  • Take the maximum of left and right depth.

FAQs

Why is null depth zero?

A null child contributes no nodes to a root-to-leaf path.

Is depth counted in nodes or edges?

This common version counts nodes. Always confirm wording if the interviewer says edges.

What is the core pattern?

Recursive height calculation.

Test your knowledge

Take a quick quiz based on this chapter.

Discussion

0 comments

Sign in to share a question or add to the discussion.
Start the discussion

Ask a question or share what stood out to you.