I have a python function for finding the preorder of Binary Search Trees.
class Node:
def __init__(self, val = 0, left = None, right = None):
self.val = val
self.right = right
self.left =
class Tree:
def __init__(self, root=None):
self.root = Node(root) if type(root) != Node else root
def add(self, val):
node = self.root
found = False
while not found:
if node.val >= val:
if node.left is None:
node.left = Node(val)
found = True
else:
node = node.left
else:
if node.right is None:
node.right = Node(val)
found = True
else:
node = node.right
def preorder(node, output = []):
output += [node.val]
if node.left is not None:
preorder(node.left, output)
if node.right is not None:
preorder(node.right, output)
return output
This works fine on the first call, but every time I run it after the data from previous calls shows up. For example:
preorder(tree.root)
[3, 3, 3, 3, 2, 1, 5, 4, 5]
preorder(tree.root)
[3, 3, 3, 3, 2, 1, 5, 4, 5, 3, 3, 3, 3, 2, 1, 5, 4, 5]
preorder(tree.root)
[3, 3, 3, 3, 2, 1, 5, 4, 5, 3, 3, 3, 3, 2, 1, 5, 4, 5, 3, 3, 3, 3, 2, 1, 5, 4, 5]
This is easily remedied by adding a empty list to the input parameters, for example:
preorder(tree.root, [])
[3, 3, 3, 3, 2, 1, 5, 4, 5]
preorder(tree.root, [])
[3, 3, 3, 3, 2, 1, 5, 4, 5]
I have my solution to the problem, but my question is why is this occurring? The preorder function doesn't seem to be changing the state of the tree, and I would assume that output would be set to the default value of [] unless a different list is given. Any information would be appreciated. Thank you!