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
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
12 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Linked List Data Structure A linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read