I have been working on a question that calculates the sums of each branch on a binary tree and returns them in an array. Its pretty much a DFS problem in which you accumulate the solutions into an array. I am just struggling on understanding where to place the return statement in my code. I know the correct answer, I just don't know why these two snippets below aren't equivalent:
def branchTot(root):
soln = []
fin = help(root, root.value, soln)
return fin
def help(root, sums, soln):
if root.left is None and root.right is None:
soln.append(sums)
return soln
else:
if root.right is not None and root.left is not None :
help(root.left, sums + root.left.value, soln)
help(root.right, sums + root.right.value, soln)
elif root.right is not None:
help(root.right, sums + root.right.value, soln)
else:
help(root.left, sums + root.left.value, soln)
and second solution below:
def branchTot(root):
soln = []
fin = help(root, root.value, soln)
return fin
def help(root, sums, soln):
if root.left is None and root.right is None:
soln.append(sums)
else:
if root.right is not None and root.left is not None :
help(root.left, sums + root.left.value, soln)
help(root.right, sums + root.right.value, soln)
elif root.right is not None:
help(root.right, sums + root.right.value, soln)
else:
help(root.left, sums + root.left.value, soln)
return soln