What is tree depth?
How many floors does a building have? You count from the ground up to the top floor. The depth of a binary tree (also called its height) is the same idea: the number of nodes along the longest path from the root down to the farthest leaf.
An empty tree has depth 0, and a single node has depth 1, because the path is just that one node.
Empty tree: has depth 0.
Single node: has depth 1, since the path is just the root itself.
root = [3, 9, 20, null, null, 15, 7]
How deep is the tree under 3? Ask each side, take the deeper one, add 1 for this level.
Move 1 of 5
Picking the deeper branch
Say the left branch is 3 levels deep and the right branch is only 1. The deepest leaf must lie down the left side, so that is the one that counts. Add 1 for the current node on top, and the total depth is 1 + 3 = 4.
So each node asks its two sides how deep they go, takes the larger answer, and adds 1 for itself.
The larger of the two: picks whichever branch reaches farther.
Plus 1: accounts for the current node at the top.
if not root:
return 0
left = max_depth(root.left)
right = max_depth(root.right)
return 1 + max(left, right)