# Python Program to Sort using a Binary Search Tree

PythonServer Side ProgrammingProgramming

When it is required to sort a binary search tree, a class is created, and methods are defined inside it that perform operations like inserting an element, and performing inorder traversal.

Below is a demonstration of the same −

## Example

class BinSearchTreeNode:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
self.parent = None
def insert_elem(self, node):
if self.key > node.key:
if self.left is None:
self.left = node
node.parent = self
else:
self.left.insert_elem(node)
elif self.key <= node.key:
if self.right is None:
self.right = node
node.parent = self
else:
self.right.insert_elem(node)

def inorder_traversal(self):
if self.left is not None:
self.left.inorder_traversal()
print(self.key, end=' ')
if self.right is not None:
self.right.inorder_traversal()

class BinSearchTree:
def __init__(self):
self.root = None

def inorder_traversal(self):
if self.root is not None:
self.root.inorder_traversal()

new_node = BinSearchTreeNode(key)
if self.root is None:
self.root = new_node
else:
self.root.insert_elem(new_node)

my_instance = BinSearchTree()

my_list = input('Enter the list of numbers... ').split()
my_list = [int(x) for x in my_list]
for x in my_list:
print('Sorted list: ')
print(my_instance.inorder_traversal())

## Output

Enter the list of numbers... 67 54 89 0 11 34 99
Sorted list:
0 11 34 54 67 89 99

## Explanation

• The ‘BinSearchTreeNode’ class with required attributes is created.

• It has an ‘init’ function that is used to assign ‘left’, ‘right’ and ‘parent’ nodes to ‘None’.

• Another method named ‘insert_elem’ is defined that helps add nodes to the tree.

• Another method named ‘inorder_traversal’ is defined, that helps perform inorder traversal on the tree.

• Another class named ‘BinSearchTree’ is defined.

• It sets the root to ‘None.

• It has a method named ‘inorder_traversal’ that helps perform inorder traversal on the tree.

• Another method named ‘add_val’ is defined that helps add nodes to the tree.

• An instance of the ‘BinSearchTree’ is created.

• The list of numbers is taken by user.

• A tree is created using this.

• The list is sorted, and its inorder traversal is performed.

• Relevant output is displayed on the console.

Published on 16-Apr-2021 12:17:35