Binary Search Tree in C++
Last Updated : 28 May, 2024
A Binary Search Tree (BST) is a type of binary tree in which the data is organized and stored in a sorted order. Unlike, a binary tree that doesn't follow a specific order for node placement, in a binary search tree all the elements on the left side of a node are smaller than the node itself, and elements on the right side of a node are greater.
In this article, we will learn more about the binary search tree, operations performed on BST, and implementation of BST, as well as the advantages, disadvantages, and applications of binary search tree in C++.
What is a Binary Search Tree (BST)?
A Binary Search Tree (BST) is a binary tree in which every node contains only smaller values in its left subtree and only larger values in its right subtree. This property is called the BST property and every binary search tree follows this property as it allows efficient insertion, deletion, and search operations in a tree.
Conditions for a Tree to be a Binary Search Tree
For a tree to be called a binary search, it should fulfill the following conditions:
- All the nodes in the left subtree of any node contain smaller values and all the nodes in the right subtree of any node contain larger values.
- Both the left and right subtrees of any node in the tree should themselves be a BST. This means that they should follow the BST rule.
- A unique path exists from the root node to every other node.
Binary Search Tree Representation in C++
In BST, every value on the left subtree < parent node < right subtree value.
Binary Search Tree
Following are the basics terminologies used in BST:
- Children: The successor nodes of a node are called its children.
- Parent: The predecessor node of a node is called its parent.
- Root: The "beginning" node is called the root i.e. a node that has no parent.
- leaf: A node that has no children is called a leaf.
Basic Operations on Binary Search Tree
The following are the basics operations performed on a binary search tree:
Here, we will discuss the basic three operation: search, insertion and deletion in a binary search tree.
Operation | Description | Best Case Time Complexity | Average Case Time Complexity | Worse Case Time Complexity |
---|
Search | This function is used to search a given key in BST. | O(log n) | O(log n) | O(n) |
---|
Insertion | This function is used to insert values in a BST. | O(log n) | O(log n) | O(n) |
---|
Deletion | This function is used to delete the specified node from a BST. | O(log n) | O(log n) | O(n) |
---|
The space complexity for all the above operations is O(n).
1. Searching in Binary Search Tree
To search for a given key in a binary search tree, follow the below approach:
Approach:
- Start from root of BST.
- Compare the target value (value you want to search) with the root node's value:
- If the target value is equal to root node's value. Return true,
- If the target value is less than root node's value, then recurse for left as smaller values lie on leftsubtree in BST.
- Else if the target value is greater than root node's value, then recurse for right as larger value lie on rightsubtree in BST.
- Repeat the above step till no more traversal is possible
- If the target element is found anywhere, return true, else return false
2. Insertion in Binary Search Tree
In BST a new key is always inserted at leaf and property of binary search tree should be maintained. To insert a given key in a binary search tree, follow the below approach:
Approach:
- Traverse the tree to find the insertion point by comparing the value to be inserted(target value) with the current node's value. I
- If the target value is less than current node's value move to left subtree.
- If the target value is more than current node's value move to right subtree.
- Repeat the above steps until the leaf node is reached.
- Insert the new node with a target value. If the target value is less than parent node's value, insert it on the left, otherwise insert it on the right.
3. Deletion in Binary Search Tree
We have the following 3 cases while deleting a node from BST:
- Deleting a leaf node.
- Deleting a node having single child.
- Deletion a node having both children.
Approach:
- Start from the root node and search for the target node (node to be deleted), move to left if target node is less than current node and move to the right if target node is greater than current node. Repeat this step until target node is found or null node is reached.
- When the target node is found Handle the following 3 cases for deletion:
- If a target node is leaf node, simply delete it
- If a target node has 1 child, replace the target node with its child node and delete the target node.
- If a target node has 2 children
- Find the target node's inorder successor.
- Replace the target node with successor.
- Delete the inorder successor.
C++ Program to Implement Binary Search Tree
The below program demonstrates all the major operations on a binary search tree: creation, searching, insertion and deletion.
C++ // C++ Program to implement binary search tree #include <iostream> using namespace std; // Node structure for a Binary Search Tree struct Node { int data; Node* left; Node* right; }; // Function to create a new Node Node* createNode(int data) { Node* newNode = new Node(); newNode->data = data; newNode->left = newNode->right = nullptr; return newNode; } // Function to insert a node in the BST Node* insertNode(Node* root, int data) { if (root == nullptr) { // If the tree is empty, return a // new node return createNode(data); } // Otherwise, recur down the tree if (data < root->data) { root->left = insertNode(root->left, data); } else if (data > root->data) { root->right = insertNode(root->right, data); } // return the (unchanged) node pointer return root; } // Function to do inorder traversal of BST void inorderTraversal(Node* root) { if (root != nullptr) { inorderTraversal(root->left); cout << root->data << " "; inorderTraversal(root->right); } } // Function to search a given key in a given BST Node* searchNode(Node* root, int key) { // Base Cases: root is null or key is present at root if (root == nullptr || root->data == key) { return root; } // Key is greater than root's key if (root->data < key) { return searchNode(root->right, key); } // Key is smaller than root's key return searchNode(root->left, key); } // Function to find the inorder successor Node* minValueNode(Node* node) { Node* current = node; // loop down to find the leftmost leaf while (current && current->left != nullptr) { current = current->left; } return current; } // Function to delete a node Node* deleteNode(Node* root, int data) { if (root == nullptr) return root; // If the data to be deleted is smaller than the root's // data, then it lies in the left subtree if (data < root->data) { root->left = deleteNode(root->left, data); } // If the data to be deleted is greater than the root's // data, then it lies in the right subtree else if (data > root->data) { root->right = deleteNode(root->right, data); } // if data is same as root's data, then This is the node // to be deleted else { // node with only one child or no child if (root->left == nullptr) { Node* temp = root->right; delete root; return temp; } else if (root->right == nullptr) { Node* temp = root->left; delete root; return temp; } // node with two children: Get the inorder successor // (smallest in the right subtree) Node* temp = minValueNode(root->right); // Copy the inorder successor's content to this node root->data = temp->data; // Delete the inorder successor root->right = deleteNode(root->right, temp->data); } return root; } // Main function to demonstrate the operations of BST int main() { Node* root = nullptr; // create a BST root = insertNode(root, 50); root = insertNode(root, 30); root = insertNode(root, 20); root = insertNode(root, 40); root = insertNode(root, 70); root = insertNode(root, 60); root = insertNode(root, 80); // Print the inorder traversal of a BST cout << "Inorder traversal of the given Binary Search " "Tree is: "; inorderTraversal(root); cout << endl; // delete a node in BST root = deleteNode(root, 20); cout << "After deletion of 20: "; inorderTraversal(root); cout << endl; // Insert a node in BST root = insertNode(root, 25); cout << "After insertion of 25: "; inorderTraversal(root); cout << endl; // Search a key in BST Node* found = searchNode(root, 25); // check if the key is found or not if (found != nullptr) { cout << "Node 25 found in the BST." << endl; } else { cout << "Node 25 not found in the BST." << endl; } return 0; }
OutputInorder traversal of the given Binary Search Tree is: 20 30 40 50 60 70 80 After deletion of 20: 30 40 50 60 70 80 After insertion of 25: 25 30 40 50 60 70 80 Node 25 found in the BST.
Time Complexity:
Auxilliary Space:
The average time complexity for all three operations on BST is O (log n). In the worst case (Skewed BST) the time complexity can become O (n). n = number of nodes.The Space complexity for all three operations done on BST is O (1). This means no extra space or memory is required to perform these operations on a BST.
Applications of Binary Search Tree
Following are the applications of binary search tree:
- BST can be used to find(an element) and sort a collection of elements in ascending or descending order and for in it.
- BSTs are used to implement priority queues where elements are inserted based on their priority number.
- BSTs are widely used in symbol tables inside compilers.
- BST can also be used to store large datasets using a particular sort key. So, searching and accessing a specific element becomes much faster.
- The Decision trees and rule-based systems in AI use Binary search trees.
- It can be used in databases for multilevel indexing.
Advantages of Binary Search Tree
- Because of the unique properties of BST, it provides an efficient way to search an element having O(log n) time complexity.
- The In-Order Traversal of BST is always in a sorted order. So, it becomes easier to retrieve elements in sorted order in a BST.
- It can adapt to various applications by defining a custom node structure.
- Balanced Binary search tree have logarithmic height that ensures efficient operations.
- It stores only the key values, that makes them space-efficient.
Disadvantages of Binary Search Tree
- The performance of BST depends upon its balance.
- Skewed BST is the worst-case scenario where the search complexity becomes O(n), just like any other tree.
- Although operations like insertion and deletion are easy in BST, maintaining the balance of the tree is hard.
- If the tree is made by using a sorted list, then the creation can lead to a highly unbalanced BST which degrades its performance. One solution is to balance the tree after every insertion.
- Binary search tree become less efficient for very large datasets
Similar Reads
How to Read Binary Search Tree from File in C++?
A binary search tree is a hierarchical data structure in which for every node in the tree, the value of all nodes in the left subtree is less than the node's value and the value of all nodes in the right subtree is greater than the node's value. This property of the binary search tree makes it effic
4 min read
Inorder Tree Traversal of Binary Tree in C++
A binary tree is a non-linear hierarchical data structure in which each node has at most two children known as the left child and the right child. As the binary tree has non-linear structure it can be traversed in multiple ways one such way is in-order traversal which is a depth first (DFS) traversa
4 min read
Print nodes in top view of Binary Tree | Set 2
Top view of a binary tree is the set of nodes visible when the tree is viewed from the top. Given a binary tree, print the top view of it. The output nodes should be printed from left to right. Note: A node x is there in output if x is the topmost node at its horizontal distance. Horizontal distance
14 min read
How to Print Data in Binary Tree Level by Level in C++?
A binary tree is a non-linear hierarchical data structure where each node can have at most two children which are termed as left and right child. In this article, we will learn how to print data in a binary tree level by level in C++. Example Input: 10 / \ 20 30 / \ / \40 50 60 70Output:10 20 30 40
4 min read
Red Black Tree (RB-Tree) Using C++
A Red Black Tree is a self-balancing binary search tree where each node has an extra bit for denoting the color of the node, either red or black. This color coding is used to ensure that the tree remains balanced during insertions and deletions. In this article, we will learn how to implement a Red-
10 min read
Connect all nodes to their Left Neighbors in a Binary Tree
Given a Binary Tree, where each node contains an extra empty pointer initially null. The task is to connect all nodes of the binary tree to their left neighbor at the same level using this extra pointer.Examples: Input : A / \ B C / \ \ D E F Output : NULL<--A / \ NULL<--B<--C / \ \ NULL
10 min read
Iterative Boundary Traversal of Complete Binary tree
Given a complete binary tree, the task is to traverse it such that all the boundary nodes are visited in Anti-Clockwise order starting from the root. Example: Input: Output: 1 2 4 5 6 7 3 Input: Output: 18 15 40 50 100 20 30 Approach: Traverse left-most nodes of the tree from top to down. (Left boun
9 min read
Sum of nodes at maximum depth of a Binary Tree | Set 2
Given a root node to a tree, find the sum of all the leaf nodes which are at maximum depth from root node. Example: 1 / \ 2 3 / \ / \ 4 5 6 7 Input : root(of above tree) Output : 22 Explanation: Nodes at maximum depth are: 4, 5, 6, 7. So, sum of these nodes = 22 In the previous article we discussed
7 min read
Tree C/C++ Programs
Trees are hierarchical data structures that contain nodes connected by edges. They are recursive in nature, which means that they are made up of smaller instances of themselves. Various types such as binary tree, trie, etc. have different characteristics to make them suitable for different applicati
2 min read
Print leaf nodes in binary tree from left to right using one stack
Given a binary tree, the task is to print all leaf nodes of the given binary tree from left to right. That is, the nodes should be printed in the order they appear from left to right in the given tree.Examples: Input : 1 / \ 2 3 / \ / \ 4 5 6 7 Output : 4 5 6 7 Input : 4 / \ 5 9 / \ / \ 8 3 7 2 / /
8 min read