How do you find the maximum depth of a binary tree?
The depth of a tree is the length of the longest path from the root to a leaf. Recursively, the depth of a node is one plus the larger of the depths of its two subtrees, and an empty subtree has depth zero.
class TreeNode:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def max_depth(root):
if root is None:
return 0
return 1 + max(max_depth(root.left), max_depth(root.right))
tree = TreeNode(1, TreeNode(2, TreeNode(3), TreeNode(4)), TreeNode(5))
print(max_depth(tree))The output is 3. The longest root to leaf path goes through the node with value 2 and then the node with value 4, which is three nodes deep.
The mechanism is that a node's depth is entirely determined by its deeper child, so the recursion returns the maximum of two smaller subproblems. The base case of an empty subtree is what terminates the recursion, and the plus one accounts for the node itself.
The trade-off to name is the stack. The recursion nests one level per node, so a completely skewed tree with a hundred thousand nodes would exhaust the Python stack, and in a language without a growable stack it would be a crash rather than an exception. The iterative version in the next answer avoids that at the cost of a little more bookkeeping, and it is the version to reach for whenever the tree depth is not bounded by something you control.