Tree sort is a sorting algorithm that builds a Binary Search Tree (BST) from the elements of the array to be sorted and then performs an in-order traversal of the BST to get the elements in sorted order. In this article, we will learn about the basics of Tree Sort along with its implementation in Python.
What is Tree Sort?
Tree sort is a comparison-based sorting algorithm that uses a Binary Search Tree (BST) to sort elements. The algorithm inserts all elements into the BST, and then an in-order traversal of the tree retrieves the elements in sorted order.
Working of Tree Sort:
Tree sort uses the properties of BST, where each node has at most two children, referred to as the left and right child. For any given node:
- The left child's value is less than the node's value.
- The right child's value is greater than the node's value.
Tree Sort involves two main steps:
- Insertion: Insert all elements into the BST.
- Traversal: Perform an in-order traversal of the BST to extract the elements in sorted order.
Tree Sort in Python:
Step 1: Define the Node Class:
First, we define a class for the nodes of the binary search tree.
Python
class TreeNode:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
Step 2: Inserting Elements into the BST:
Next, we define a function to insert elements into the binary search tree.
Python
def insert(root, key):
if root is None:
return TreeNode(key)
if key < root.val:
root.left = insert(root.left, key)
else:
root.right = insert(root.right, key)
return root
Step 3: In-Order Traversal of the BST:
The in-order traversal function will visit all nodes of the BST in sorted order and collect the elements.
Python
def inorder_traversal(root, res):
if root:
inorder_traversal(root.left, res)
res.append(root.val)
inorder_traversal(root.right, res)
Step 4: Tree Sort Function:
Now, we combine the insertion and in-order traversal steps to implement the tree sort function.
Python
def tree_sort(arr):
if not arr:
return arr
root = None
for key in arr:
root = insert(root, key)
sorted_arr = []
inorder_traversal(root, sorted_arr)
return sorted_arr
Complete implementation of Tree Sort in Python:
Here is the complete implementation of tree sort in Python:
Python
class TreeNode:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
def insert(root, key):
if root is None:
return TreeNode(key)
if key < root.val:
root.left = insert(root.left, key)
else:
root.right = insert(root.right, key)
return root
def inorder_traversal(root, res):
if root:
inorder_traversal(root.left, res)
res.append(root.val)
inorder_traversal(root.right, res)
def tree_sort(arr):
if not arr:
return arr
root = None
for key in arr:
root = insert(root, key)
sorted_arr = []
inorder_traversal(root, sorted_arr)
return sorted_arr
# Example usage
arr = [5, 3, 7, 2, 8, 1, 4, 6]
sorted_arr = tree_sort(arr)
print("Sorted array:", sorted_arr)
OutputSorted array: [1, 2, 3, 4, 5, 6, 7, 8]
Time Complexity: O(nlogn) on average, but it can degrade to O(n^2) if the tree becomes unbalanced (e.g., if the input array is already sorted).
Auxiliary Space: O(n)
Similar Reads
B Tree in Python A B-tree is a self-balancing tree data structure that maintains sorted data and allows searches, sequential access, insertions, and deletions in logarithmic time. B Tree in Python Table of Content Characteristics of B-TreesTraversal of B-Tree in PythonSearch operation in B Tree in PythonInsert opera
14 min read
B+ Tree in Python In computer science, data structures are crucial in efficiently managing and organizing data. Among these, the B+ tree is a powerful and important data structure, widely used in databases and file systems. In this article, we will discuss the concept of B+ trees, exploring their structure, operation
12 min read
AVL Tree in Python The AVL tree in Python is a selfâbalancing binary search tree that guarantees the difference of the heights of the left and right subtrees of a node is at most 1. The algorithm is named after its inventors, Georgy Adelson-Velsky, and Evgenii Landis who published their paper in 1962. The AVL tree kee
6 min read
Red Black Tree in Python Red Black Tree is a self-balancing binary search tree where each node has an extra bit representing its color, either red or black. By constraining how nodes are colored during insertions and deletions, red-black trees ensure the tree remains approximately balanced during all operations, allowing fo
11 min read
Binary Search Tree In Python A Binary search tree is a binary tree where the values of the left sub-tree are less than the root node and the values of the right sub-tree are greater than the value of the root node. In this article, we will discuss the binary search tree in Python.What is a Binary Search Tree(BST)?A Binary Searc
11 min read