How the maximum-depth recursion works
The depth of an empty tree is 0. The depth of any other node is 1 plus the larger of its two subtrees’ depths. So the function calls itself on the left child, then on the right child, and only once both have returned can it compute its own answer.
The Python example builds a tree from 50, 30, 70, 20, 40, 80, 10 and returns 4 — the path 50 → 30 → 20 → 10. The Java version is a LeetCode solution exactly as you would submit it, with no main method; the visualizer supplies the TreeNode class and a sample tree so it runs as written.
What to watch for when it runs
- The call stack holds one frame per node on the current path from the root.
- Each node’s depth is drawn travelling back up to its parent as the call returns.
- Null children return 0 straight away — the base case every other answer is built on.
Time and space complexity
- Time
- O(n)
- Space
- O(h)
Every node is visited once. The stack is as deep as the tree is tall: O(log n) when balanced, O(n) when it degenerates into a chain.