This relates to how Python is both pass by reference or pass by value depending on if the object is immutable or not. I'm able to traverse a binary tree recursively and print out all the values, but it's a little more difficult if I want to instead return a specific element. In the code below, I'm (twice) trying to return a node if its data attribute matches the integer passed in. n1 and n2 are those int values.
def get_node(self, d, root, n=[]):
if (root == None):
return
else:
if(root.data == d):
n.append(root)
self.get_node(d,root.left)
self.get_node(d, root.right)
return n
def tree_traversal(self, n1, n2):
n1 = self.get_node(n1,self.root)[0]
n2 = self.get_node(n2,self.root)[1]
print(n1.data)
print(n2.data)
return self.helper(n1,n2)
This works, and I get a list that contains the node objects I'm looking for. However, if instead of returning (and passing as an argument) a list, I use a string, or a None object to later be changed, this doesn't work. I assume that's because lists are mutable while strings are not. What's more, you'll see I have to assign n[1] to n2 because for some reason, even after exiting the get_node recursive call and doing it all over again for n2, the returned list still contains n1 in the 0th index.
Can someone please explain why the list is still modified when assigning to n2? And is there a way to instead of passing as argument and returning an empty list n, passing as argument and returning a regular object that has default value None?