As the title suggested, i am still a newbie for programming and met this recursion algorithm and got stuck for 3-4 hours and still cannot figure out how the recursion works
The task is:(sorry for the picture rather than the text since they dont allow users to copy and paste)
The solution for this is:
class BinaryTree:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def branchSums(root):
sums = []
calculateBranchSums(root, 0, sums)
return sums
def calculateBranchSums(node, runningSum, sums):
if node is None:
return
newRunningSum = node.value + runningSum
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 actually understand the logic here but I am really confuse on two points:
(1) when we use sums
initially as a empty list to function calculateBranchSums
, how does it modify the sums
list without returning and reassigning to the sums
;
(2) why all the return
in calculateBranchSums
function returns nothing;