SDE & MLE Prep

104. Maximum Depth of Binary Tree

Problem

Return the maximum depth of a binary tree: the number of nodes on the longest path from the root down to a leaf.

Example: [3,9,20,null,null,15,7] → 3

depth(node) = 1 + max(depth(left), depth(right)), depth(None) = 0.

Complexity: O(n).

class Solution:
    def maxDepth(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
        return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))