Algorithms · Trees & recursion
Maximum Depth of a Binary Tree
Count the levels of a tree.
The problem
Return how many levels the tree has: the number of nodes on the longest path from the top down to a leaf. LeetCode sends the tree as a list, row by row, with None for gaps; build turns it into a real tree for you.
check([3, 9, 20, None, None, 15, 7])→3check([1, None, 2])→2Now ask: what if there were a billion?
Trees are everywhere: the folders on your Mac, the web page you’re reading (the DOM), and Git, which stores your whole project as a tree of fingerprints (a Merkle tree).
Aim for O(n)🌱 warm-up
Think it through
You know how deep the left and right subtrees are. How deep is the whole tree?
- Left + right
- 1 + the deeper of the two
Show the answer
1 + the deeper of the two. This node adds one level on top of its deeper child. Answering a tree question from its children’s answers is recursion.
When does the recursion stop?
- At an empty tree (None): depth 0
- When the tree is balanced
Show the answer
At an empty tree (None): depth 0. Every recursion needs a base case that answers without recursing. Empty trees have depth 0, and everything builds up from there.
Stuck? 3 nudges, smallest first
- A tree is a node with two smaller trees hanging off it. If you knew how deep each smaller tree was, could you answer?
- The depth is 1 (this node) plus the depth of the deeper child.
return 1 + max(max_depth(root.left), max_depth(root.right))
The fast way
Try it yourself before you open this.
Show the fast version
def max_depth(root):take the top of a tree if root is None:an empty tree… return 0…has no levels return 1 + max(max_depth(root.left), max_depth(root.right))this level, plus the deeper sideWhere it’s used for real
Solve it yourself.
It runs right in the page: the tests, the gremlins that try to break it, and a race up to a billion. Free, nothing to install.