104. Maximum Depth of Binary TreeΒΆ
The depth of a binary tree is defined as the length of the longest path from the root to any leaf. This naturally suggests a recursive, bottom-up way of thinking.
For any given node, if we already know the maximum depth of its left and right subtrees, then the depth of this node is simply one (for the current node) plus the larger of those two depths. This breaks the problem into identical subproblems on smaller trees.
The base case occurs when we reach a None node, which contributes a depth of 0. As the recursion unwinds, each node
computes its depth using the results from its children, and the maximum value propagates back up to the root.
Pseudocode
Runtime Complexity
Time: \(O(n)\)
Space: \(O(h)\)