0

I wanna find the lower ancestor in a binary tree, and what i do is first, list the fathers of each node, then compare the list and the last item in common is the lower ancestry.

I have this code:

def ancesters(self, node, list= []):
    if self.seekNode(node) != False:
        if node < self.id:
            list.append(self.id)
            return self.left.ancesters(node)
        elif node > self.id:
            list.append(self.id)
            return self.right.ancesters(node)
        elif self.id == node:
            list.append(self.id)
            return list
    else:
        return False

the function seekNode works, and this method too, but when i use the method twice, shows the list of ancestor of the last call, example:

i have this tree:

               2
               |
                ---
                   5
                  ---
                 3   6

and when i call the method ancesters(6), the list will be (2,5,6), and when i call again to search the fathers of 3, shows (2,5,6,2,5,3).

so, when i set the parameter (list=[]) why the list does not initialize and save the list value?. I call the method with the same object, in this case will be the node (root) of the tree. the nodes are instance of the node (root) of the tree.

Ernesto
  • 129
  • 2
  • 10

1 Answers1

0

In short, do not use mutable object (like list) as a default value. This is Anti-Pattern, because in Python the default value is shared between all function calls. so it must be immutable. popular option is None and condition if not None: ...

You can also read here

Lior Cohen
  • 5,570
  • 2
  • 14
  • 30