Below is my implementation of a BST in python:
class Node:
def __init__(self,value):
self.value = value
self.left = None
self.right = None
class BinarySearchTree:
def __init__(self):
self.root = None
def insert(self,value):
new_node = Node(value)
if self.root is None:
self.root = new_node
return True
temp = self.root
while (True):
if new_node.value == temp.value:
return False
if new_node.value < temp.value: #left
if temp.left is None:
temp.left = new_node
return True
temp = temp.left
else: #right
if temp.right is None:
temp.right = new_node
return True
temp =temp.right
def contains(self,value):
temp = self.root
while (temp is not None):
if value < temp.value:
temp = temp.left
elif value > temp.value:
temp = temp.right
else:
return True
return False
def print_tree(self, level=0):
if self.root is not None:
self.print_tree(self.root.right, level + 1)
print(" " * level + "->", self.root.value)
self.print_tree(self.root.left.value, level + 1)
To run it I use these commands:
my_tree = BinarySearchTree()
my_tree.insert(2)
my_tree.insert(1)
my_tree.insert(3)
But for some reason I get this error when I run 'my_tree.print_tree()'
Any suggestions are welcome.
I was expecting this output to pop out:
-> 3
-> 2
-> 1
I'm guessing it most likely has something to do with the recursive call in the print_tree method.