← Problem setPython
#104EasyTrees & BST
Maximum Depth of Binary Tree
The tell: A value that each subtree can compute and hand upward.
How you get there
- 1Depth of a node is one plus the deeper of its two subtrees.
- 2An empty node contributes zero.
- 3This is the template for almost every 'return something from each subtree' tree problem.
Solution
def max_depth(root) -> int:
if not root:
return 0
return 1 + max(max_depth(root.left), max_depth(root.right))- Time
- O(n)
- Space
- O(h)
What goes wrong
Returning 0 for a leaf instead of 1 shifts every answer by one; decide the convention first.