How deep does a binary tree go? Ask each child for its depth, take the bigger one and add one for yourself.
▼The problem
LeetCode 104 (Easy). Given the root of a binary tree, return its maximum depth: the number of nodes on the longest path from the root down to a leaf.
Example (the mine, as in the original): ruby at the root; sapphire (left) and emerald (right) below it; under the sapphire, amethyst (left) and topaz (right); under the amethyst, only a right child, the diamond. As level order with the gems standing in for values: [ruby, sapphire, emerald, amethyst, topaz, null, null, null, diamond]. Ruby → sapphire → amethyst → diamond is 4 nodes; the emerald side is 2.
def maxDepth(node):
if node is None:
return 0
left = maxDepth(node.left)
right = maxDepth(node.right)
return 1 + max(left, right)TRY IT ON LEETCODE ▶The solution
def maxDepth(node):
if node is None:
return 0
left = maxDepth(node.left)
right = maxDepth(node.right)
return 1 + max(left, right)Transcript
Maximum Depth of Binary Tree. You're given the root of a binary tree. Return its maximum depth: the number of nodes on the longest path from the root down to a leaf, a node with no children.
Here's our tree, drawn as a mine. A ruby at the top, with a sapphire and an emerald below it. Under the sapphire, an amethyst and a topaz. And under the amethyst, one more gem: a diamond. Ruby, sapphire, amethyst, diamond: that's four nodes deep. The emerald side is only two. So the answer is four.
One way is to walk every path from the top and count its length. But the paths share tunnels. Here the ruby gets dug three times and the sapphire twice: nine visits for six gems. In a big mine, that repeated digging piles up.
Instead, let each node answer for itself. An empty spot has depth zero. Any other node asks its left child and its right child for their depths, keeps the bigger answer, and adds one for itself. The answers bubble up from the bottom.
In code, that's a few lines. If the node is None, return zero. Otherwise, find the depth of the left side, then the right side, and return one plus the larger of the two.
Let's dig in. The ruby asks the sapphire, which asks the amethyst. The amethyst's left is empty: zero. Its right is the diamond, whose children are both empty, so the diamond returns one. The amethyst keeps one, plus one: two. Back at the sapphire, the topaz returns one. The sapphire keeps two, plus one: three. Then the emerald returns one. Finally, the ruby keeps three, plus one: four.
Each node is visited exactly once, so the time is O of n. The extra space is the call stack, one call per level of the path we're on: O of h, the tree's height. In a lopsided tree, that can be all n nodes.
Ask both sides, keep the bigger, add one. That's Maximum Depth of Binary Tree.