Here is the solution:
function maxDepth(root):
if root is null:
return 0
left = maxDepth(root.left)
right = maxDepth(root.right)
return 1 + max(left, right)
This is the simplest tree DP. You do not need extra arrays or global variables. The recursion stack handles everything. Each call returns an integer, and you combine results as you return.
This runs in time and uses space.