Your implementation has some problems:
The tree can only have 3 nodes, since you never create a grand-child of the root, but always make the new node either the root, or one of its children
left/right are reversed: you should insert smaller values to the left.
In the main program code, you should only use the insert
method, never the insert_after_root
.
Here is a correction of your implementation, based on recursion (putting a method on the Node
), and an additional set of methods for producing a string representation, 90° tilted (with the root displayed at the left).
class Node:
def __init__(self,value):
self.value = value
self.left = None
self.right = None
def insert_after(self, value):
if value < self.value:
if self.left:
self.left.insert_after(value)
else:
self.left = Node(value)
elif value > self.value:
if self.right:
self.right.insert_after(value)
else:
self.right = Node(value)
else:
raise ValueError("this tree doesn't accept duplicates")
def __repr__(self):
lines = []
if self.right:
found = False
for line in repr(self.right).split("\n"):
if line[0] != " ":
found = True
line = " ┌─" + line
elif found:
line = " | " + line
else:
line = " " + line
lines.append(line)
lines.append(str(self.value))
if self.left:
found = False
for line in repr(self.left).split("\n"):
if line[0] != " ":
found = True
line = " └─" + line
elif found:
line = " " + line
else:
line = " | " + line
lines.append(line)
return "\n".join(lines)
class Binary_search_tree:
def __init__(self):
self.root=None
def insert(self,value):
if self.root==None:
self.root=Node(value)
else:
self.root.insert_after(value)
def __repr__(self):
return repr(self.root)
bst = Binary_search_tree()
bst.insert(4)
bst.insert(2)
bst.insert(8)
bst.insert(3)
bst.insert(5)
bst.insert(7)
bst.insert(10)
print(str(bst))