Binary search tree
class Node:
def __init__(self, data=None, right=None, left=None):
self.data = data
self.right = right
self.left = left
def __str__(self):
return str(self.data)
def insert_data(self, value):
if value < self.data:
if self.left is None:
self.left = Node(data=value)
else:
self.left.insert_data(value)
else:
if self.right is None:
self.right = Node(data=value)
else:
self.right.insert_data(value)
def contains(self, value):
if value == self.data:
return True
else:
if value < self.data:
if self.left is None:
return False
else:
return self.left.contains(value)
else:
if self.right is None:
return False
else:
return self.right.contains(value)
def in_order(self):
if self.left:
self.left.in_order()
print(self.data)
if self.right:
self.right.in_order()
def pre_order(self):
print(self.data)
if self.left:
self.left.pre_order()
if self.right:
self.right.pre_order()
def post_order(self):
if self.left:
self.left.post_order()
if self.right:
self.right.post_order()
print(self.data)
if __name__ == '__main__':
a = Node()
a.data = 10
a.insert_data(15)
a.insert_data(5)
a.insert_data(8)
a.in_order()
print('\n')
a.pre_order()
print('\n')
a.post_order()
print(a.contains(8))