LeetCode 104: Maximum Depth Of Binary Tree — Step-by-Step Visual Trace


Easy — Binary Tree | Depth-First Search | Recursion | Tree

The Problem

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

Approach

This solution uses a recursive depth-first search approach. For each node, it recursively calculates the maximum depth of both left and right subtrees, then returns the maximum of these two depths plus one for the current node.

Time: O(n) · Space: O(h)

Code

class Solution:
    def maxDepth(self, root: TreeNode) -> int:
        if not root:
            return 0

        left_depth = self.maxDepth(root.left)
        right_depth = self.maxDepth(root.right)

        return max(left_depth, right_depth) + 1

Watch It Run

Try it yourself: Open TraceLit and step through every line.


Built with TraceLit — the visual algorithm tracer for LeetCode practice.


Comments