I am trying to clarify my understanding of the differences between these two code snippets which find maximum depth of binary tree. ( for simplicity I didnt inlcude the class )
So the reason the first code variable will always be 1 is becuase its not an object its just a variable, so when I pass it into the functions a new 'version' of it is created.
Whereas in the second code example the function use a refferene to the same array object.
Does this mean python 3 is pass by value for variables and by refference for objects ?
def maxDepth(self, root: TreeNode) -> int:
if not root:
return 0
max_depth = 1
self.check_depth(root.left, max_depth, 1)
return max_depth
def check_depth(self, node, max_depth, curr_depth):
if not node:
return
curr_depth += 1
self.check_depth(node.left, max_depth, curr_depth)
self.check_depth(node.right, max_depth, curr_depth)
max_depth = max(max_depth, curr_depth)
return
Here the instance variable is replaced by array object.
def maxDepth(self, root: TreeNode) -> int:
if not root:
return 0
max_depth = [1]
self.check_depth(root.left, max_depth, 1)
return max_depth[0]
def check_depth(self, node, max_depth, curr_depth):
if not node:
return
curr_depth += 1
self.check_depth(node.left, max_depth, curr_depth)
self.check_depth(node.right, max_depth, curr_depth)
max_depth[0] = max(max_depth[0], curr_depth)
return
Thank you