What is Maximum Depth
The depth of the tree is the number of nodes on the longest path from the root to a leaf. A single node has depth 1. An empty child has depth 0.
1 2 3 4 depth 3
Approach
Ask each child for its depth, then add one for the current node. The larger child decides the answer.
The picture labels each finished node with the depth it returns. The highlighted node is the one being computed.
Interactive solution
The finished tree is on screen when the page opens. Next and Play start again from the first step. The play controls sit under the tree and the pseudocode.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Time | O(n) | Each node is visited once. |
| Call stack | O(h) | A spine of n nodes uses n calls. |
Implementation
def depth(node):
if not node:
return 0
return 1 + max(depth(node.left), depth(node.right))