educative.io

Tthe integer variable not able to pass through the recursive calls

Hello.

While I understand and like the solution for this question, I was wondering what went wrong with my approach which follows the solution from the previous problem - All Paths for a Sum.

def find_sum_of_path_numbers(root):
total = 0
find_path_recursive(root,[],total)
return total

def find_path_recursive(node,cur_path,total):
if node is None:
return
cur_path.append(str(node.val))
if node.left is None and node.right is None:
total += int(’’.join(list(cur_path)))
else:
find_path_recursive(node.left,cur_path,total)
find_path_recursive(node.right,cur_path,total)
del cur_path[-1]

The result returned 0 for the above code.

Thank you so much for explaining in advance. Much appreciated.


Type your question above this line.

Course: https://www.educative.io/collection/5668639101419520/5671464854355968
Lesson: https://www.educative.io/collection/page/5668639101419520/5671464854355968/5675214360805376

Hi @Sherry_Pan

Here you are reaching your root node and returning the path sum. But the functions calling these functions recursively are not returning any value.

Even when you will fix the above issue, then there will be the last thing you have missed which is

The value of total is 0, and you return the total without updating it. Over here, you have made the widespread mistake considering total is sent by reference, but in fact, it is sent by value.

If you have any other queries, please feel free to ask. Thanks.

1 Like

Thank you so much for the detailed explanation, much appreciated!

def find_sum_of_path_numbers(root):
total = [0]
find_path_recursive(root,[],total)
return total[0]

def find_path_recursive(node,cur_path,total):
if node is None:
return
cur_path.append(str(node.val))
if node.left is None and node.right is None:
total[0] += int(’’.join(list(cur_path)))
else:
find_path_recursive(node.left,cur_path,total)
find_path_recursive(node.right,cur_path,total)
del cur_path[-1]

As suggested, since integer is immutable, we can’t really use the sent by reference method. I have changed variable total to a list holding only one element. With that, since each function is updating the reference, the functions don’t need to recursively return anything and the above function should work. I have tested it and it gave the right answer. Please let me know if I missed anything here. Thank you so much.