I was solving some problems on Binary tree and I got stuck in this question https://www.geeksforgeeks.org/sum-nodes-longest-path-root-leaf-node/ I am using python to solve the question I understood the logic of the solution given on the link but my question is how did the value of maxSum change in the SumOfLongRootToLeafPathUtil(root) function when nothing is returned from SumOfLongRootToLeafPath() function how is the original value of the varaible change please help ps:Please refer to the python code given in the link
The maxSum list object passed into the SumOfLongRootToLeafPath
function is mutable. So, when it is changed within that function, the SumOfLongRootToLeafPathUtil
function will see the changes to it. So, there is no need to return a value.
e.g. showing mutable nature of a list
def change_it(value):
value[0] = 12 # modify the list without creating a new one
value = [4]
print(value) # this will show [4]
change_it(value)
print(value) # this will show [12] as change_it has altered the value in the list
If a tuple had been used for maxSum rather than a List, then it would be necessary to return the result from SumOfLongRootToLeafPath
as tuples are immutable.
e.g. showing immutable nature of a tuple
def change_it(value):
value = (12, ) # can't modify the tuple, so create a new one
value = (4, )
print(value) # this will show (4,)
change_it(value)
print(value) # this will still show (4,) as change_it cannot modify the tuple