Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Python Program to Sort using a Binary Search Tree
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.keyOutput
Enter the list of numbers... 67 54 89 0 11 34 99 Sorted list: 0 11 34 54 67 89 99Explanation
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.
