To sum up all the nodes' depths in any given binary tree, I've written the following recursive algorithm:
def nodeDepths(root): final= helper(root,0, final) return final def helper(node,d, final): if not node: return final+= 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 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?