0

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
    
D.K
  • 29
  • 6
  • 1
    `answer` does not update when called inside `maxDepth()` – Andrew Ryan May 29 '22 at 22:07
  • Do you mean that you expect that assigning to a variable inside a function has an effect outside the function? – mkrieger1 May 29 '22 at 22:07
  • 1
    Does this answer your question? [How do I pass a variable by reference?](https://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference) – mkrieger1 May 29 '22 at 22:12
  • @AndrewRyan I thought calling maxDepthHelper function inside maxDepth function will update the answer variable? – D.K May 29 '22 at 22:14
  • @mkrieger1 so if I passed an array it will be updated but not a variable like int will be updated like this? – D.K May 29 '22 at 22:16
  • @D.K the variable is local to the function as its not part of the class, and if it was part of the class you would have to check that the `self.answer` is not being overwritten with a smaller umber with a different branch. – Andrew Ryan May 29 '22 at 22:19

0 Answers0