0

Suppose I am given a list of values, say [13, 12, 15] and a tree of following with leafs 3, 2, 5.

Following is my code to find each leaf from left to right and update the leaf value. Therefore, it is a postorder traversal.

tree - tree with a root.

current_leaf_list - a list of values that I have to use in order to update the leaf values in tree.

Not sure what happens here. My list is updating but when I updated the first value in current_leaf_list, I tried to update current_leaf_list with current_leaf_list[1:].

But when I do the recursion, current_leaf_list returns to its previous version.

def recurse(tree, current_leaf_list):
  if not tree:
    return

  if tree.symbol is not None:
    tree.symbol = current_leaf_list[0]
    current_leaf_list = current_leaf_list[1:]

  recurse(tree.left, current_leaf_list)
  recurse(tree.right, current_leaf_list)

Any idea why this happens?

baduker
  • 19,152
  • 9
  • 33
  • 56
Kevin Lu
  • 39
  • 6
  • 2
    Since `current_leaf_list` is a parameter to the function and therefore local, updating it inside the function won't reflect changes to the outside. If you want to use the sliced list in further recursion steps, pass it to the function call in the last two lines like `recurse(tree.left, current_leaf_list[1:])` – redevined Mar 20 '18 at 18:44
  • Pleas post all relevant code in order to create a [\[SO\]: How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). Also how would you like to update the leaf value? Add a proper description (maybe with examples). – CristiFati Mar 20 '18 at 18:48

0 Answers0