To sum up all the nodes' depths in any given binary tree, I've written the following recursive algorithm:
def nodeDepths(root):
final=[0]
helper(root,0, final)
return final[0]
def helper(node,d, final):
if not node:
return
final[0]+= d
helper(node.left,d+1, final)
helper(node.right,d+1, final)
class BinaryTree:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
My thinking was: as I see each node, add the depth of that node to the final sum, then recursively call on the left and right with final
list as an argument. At the end of the recursive call stack, final[0]
should have the right value.
Is there a better way to do this? I have concerns about thread safety in general with global variables but is it a better practice to use global variables in this case?