I am really sorry for asking this simple question. I am currently solving algorithms and got stuck in branch sum. I searched a lot around but nobody actually explained the actual code, just the concept. If anyone here will be kind enough to explain it to me.
class BinaryTree:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def branchSum(root):
sums = []
calculateBranchSum(root, 0, sums)
return sums
def calculateBranchSums(node, runningSum, sums):
if node is None:
return
newRunningSum = runningSum + node.value
if node.left is None and node.right is None:
sums.append(newRunningSum)
return
calculateBranchSums(node.left, newRunningSum, sums)
calculateBranchSums(node.right, newRunningSum, sums)
I am mainly confused on how the node goes back? Like first with node.left, we receive the final sum. Then with node.right, newRunningSum is last sum?
runningSum) and a list (sums) to track the cumulated sums per branch. The number is used to pass the value down in the recursive chain, the list to pass it up as it is mutable.