I was trying to solve this max depth of the binary tree question using top-down approach. However, for some reason my answer variable is not being updated. My answer variable which is supposed to print the max depth returns 0. I am not able to understand why this is happening?
def maxDepthHelper(root, depth, answer) -> int:
if root is None:
return
if root.left is None and root.right is None:
answer = max(answer, depth)
return
maxDepthHelper(root.left, depth + 1, answer)
print(answer)
maxDepthHelper(root.right, depth + 1, answer)
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
answer = 0
maxDepthHelper(root, 1, answer)
return answer