You might have learned about different Data Structure concepts like Array, Stack, Queue, etc. which fall under the Linear Data Structure concept. Moving ahead, you will find a Non-Linear Data Structure where the โBST in C++โ is worthful to get noted.
BST stands for Binary Search Tree which is a predominantly a part of the Tree Data Structure concept. You might know the Tree Concept in Data Structure. However, if you are unaware of Tree and BST in C++, this article will be the best you are looking for.
So, get ready to understand the extensive discussion about the Binary Search Tree BST in CPP along with its properties & different operations.
Summary or Key Highlights:ย
- BST stands for the Binary Search Tree which is a part of the Tree Data Structure concept.
- In BST, there are three types of Nodes present, Root Node, Right Node & Left Node.
- The BST is similar to an ordinary Tree Structure; just there are some unique properties present.
- The Node insertion into the BST can only be done with the Structure Concept.
- The role of the Pointer to make Left & Right Subtree is most important.
- On BST, we can perform Search & Delete operation on any Node.
What Is BST In Data Structure? Read More
Data Structures are mainly two types. One is Linear & the other is the Non-Linear. The Tree is a type of Non-Linear Data Structure. In the Tree Data Structure, the data is being stored in different positions, not in a continuous manner.
In Tree Structure, there are two types of Nodes present. One is the Root Node or Main Node & others are the Leaf Node. The Root Node is placed at the top of any tree where the Leaf Nodes are the remaining lower side Nodes.
In any Tree Structure, if Two Leaf Nodes exist in every Root Node, then the Tree will be called the Binary Tree. BST is a part of the Binary Tree Concept.
BST stands for theย Binary Search Tree. As the name suggests it is one type of Binary Tree. It is an important fundamental type of Data Structure. BST in C++ highly follows the properties of the Binary Tree.
What Are The Properties Of Binary Search Tree?
There is no doubt that the Binary Search Tree is one kind of Tree, but we can say that โAll BSTs are the Trees, but all Trees are not BSTsโ. This is because some properties are being followed by the BST. The properties are the following:
- The left Subtree of the BST will only have values that are less than the Root Node Value.
- The Right Subtree of the BST will only have Values that are greater than the Root Node Value.
- All the values in the Left Subtree will be less than the Main Root Node. All the values in the Right Subtree will be higher than the Main Root Node.
- In the Binary Search Tree, we canโt include any duplicate values.
- You will find the Left & Right Subtree will develop each BST itself.
Is it appearing difficult? Letโs try to know more wisely using the below image.
Here, in the above image, the left-sided image is a correct BST. But the right-sided tree is not in the correct manner.ย
Why is it so? Let’s know it.
We can see a Subtree there where the Root Node is 3. It has 1 as Left Child & 6 as Right Child. In this particular Subtree, the problem arises.
According to the rule, BST will have a greater numbered node all on the Right Side. But we can see that the left side of the Subtree which has the Root Node as 6 has 2 as their Left Child.
The number 2 is not applicable there. There the number is applicable which is greater than 3 but less than 6 as we can see in the image which is on the left-hand side. There instead of 3, we have used 4 as the node value. Hence, it is a correct representation of BST.ย
How To Do Implementation Of BST?
BST in C++ has some unique implementation processes. Here we first need to have the nodes of the Tree in Array format. Then we consider the first or last number as the root of the Main Tree. Then depending upon the number, we have to define the BST. The methods go in the following way:
- Consider the first number as the Root Node.
- Check the next number.
- If the number is lesser or equal to the value of the Root, then it will be on the Left Side of the Tree.
- If the number is greater or equal to the value of the Root, then it will be on the Right Side of the Tree.
Suppose, we have given an Array as {3,2,1,7}. Now as per the rule, we will consider the 3 as the Root value. As the next number 2 is less than the value 3, it will be on the left side of the Tree. And as the 1 number is less than both the numbers 3 & 2, so it will be the left child of 2. Then as the number 7 is highest than all. So it will be the Right Child of the Main Tree.
ย If youโre interested in knowing about arrays in other programming languages like Java, then you start with knowing the basic difference betweenย Array vs ArrayList.
How To Implement Or Insert Elements In Binary Search Tree In C++?
Now, we are going to discuss the core concept of the topic. Here, we will discuss the Implementation process of Binary Search Tree using C++ Programming Language. We can term this implementation process as the Insertion Operation on BST.
The BST can only be developed when you will insert Nodes in the Tree. So, the BST Implementation is none other than the Insertion Operation on BST. Let us check the following code & its implementation Process.
#include
#include
using namespace std;
// Constructing The Tree
struct Node{
int data;
struct Node *left;
struct Node *right;
Node(int val){
data=val;
// Assigning the left and right nodes NULL
left=NULL;
right=NULL;
}
};
// Function To Implement BST
Node* sortedBST(int arr[],int start , int end){
if(start>end)
return NULL;
// Assinging The Mid Value
int mid = (start+end)/2;
// Assinging The Mid Value As Root Node
Node* root = new Node(arr[mid]);
// Construct Left & Right Subtree
root->left = sortedBST(arr, start, mid-1);
root->right = sortedBST(arr, mid+1 , end);
return root;
}
// Function To Print Pre-Order Traversal
void preorder(Node* root){
if(root==NULL)
return;
// Following The N-L-R Rule
cout<data<<" ";
preorder(root->left);
preorder(root->right);
}
int main()
{
// Assinging The Array.
int arr[] ={3,2,1,7,9};
int len = sizeof(arr)/sizeof(int);
// Function Calling
Node *root = sortedBST(arr,0,len-1);
// Printing The Data In Preorder
cout << "The BST Is: " << endl;
preorder(root);
return 0;
}
Steps Of The Program:ย
- At first, the Node Structure will be developed where the Integer Value & two Pointers will be used.
- Then in the Main Function, we will provide the list of data in the Array. And from the Array, the data will be collected.
- We will share the Array along with Starting & Ending points to get the complete tree.
- In the User-Defined Function, we will set the Middle of Array as the Main Root Node.
- Now, according to the rule, we will put the data into the Tree taken from Array.
- When the Tree Structure is completed, we will call the Preorder() Function.
- The Preorder is one kind of Traversal process where the Node is printed first. It follows the NLR policy to print the Tree.
Output:ย
From the above output, we can see that a Series of Numbers are coming which are the Nodes of the BST. As we are using the Preorder Traversal, the first Main Root Node will be printed first & later the Left Subtree will be evaluated.
Did you face any difficulty understanding the code? Donโt worry, you can get help from reliableย C++ programming homework expertsย and clear all your doubts.
How To Use Different Traversal Methods In Binary Search Tree?
Now, in the above case, we have seen the process to implement BST using C++ language. You might have noticed that we are using the Tree Traversal Method to print in any sequence. In the above case, we have used the Preorder Traversal Method.
Whereas for the Printing of the BST, there are three different Traversal Methods present. They are Preorder Traversal, Inorder Traversal & Postorder Traversal. All of these traversals got their name from the Position of the Root Node Printing. Let us check each one of them.
Preorder Traversal:
In this case, the Root Node will be printed at the first. It follows the N-L-R Method. That means the Root Node(N) will be printed first, later the last Node of the Left Tree (L) & last Node of the Right Tree (R).Inorder Traversal:
In this case, the Root Node will be printed in the Middle. At first, the last Node of the Left Tree (L) will be printed & when all the Nodes of the Left Tree are complete, the Main Root Node (N) will be printed. At last, the right tree will be evaluated in the same way.Postorder Traversal:
Here, the Main Root Node (N) will be printed at the very end. First, the Left Node (L) will be printed, then the Right Node (R). At the end, the Main Root Node (N) will be printed. It follows the L-R-N Method.
C++ Program To Understand Different Traversal Methods On Binary Search Tree:
#include
#include
using namespace std;
// Constructing The Tree
struct Node{
int data;
struct Node *left;
struct Node *right;
Node(int val){
data=val;
// Assigning the left and right nodes NULL
left=NULL;
right=NULL;
}
};
// Function To Implement BST
Node* sortedBST(int arr[],int start , int end){
if(start>end)
return NULL;
// Assinging The Mid Value
int mid = (start+end)/2;
// Assinging The Mid Value As Root Node
Node* root = new Node(arr[mid]);
// Construct Left & Right Subtree
root->left = sortedBST(arr, start, mid-1);
root->right = sortedBST(arr, mid+1 , end);
return root;
}
// Function To Print Pre-Order Traversal
void preorder(Node* root){
if(root==NULL)
return;
// Following The N-L-R Rule
cout<data<<" ";
preorder(root->left);
preorder(root->right);
}
// Function To Print In-Order Traversal
void inorder(Node* root){
if(root==NULL)
return;
// Following The L-N-R Rule
inorder(root->left);
cout<data<<" ";
inorder(root->right);
}
// Function To Print Post-Order Traversal
void postorder(Node* root){
if(root==NULL)
return;
// Following The L-R-N Rule
postorder(root->left);
postorder(root->right);
cout<data<<" ";
}
int main()
{
// Assinging The Array.
int arr[] ={3,2,1,7,9};
int len = sizeof(arr)/sizeof(int);
// Function Calling
Node *root = sortedBST(arr,0,len-1);
// Printing The Data In Preorder, Inorder & Postorder
cout << "The Preorder Of BST Is: " << endl;
preorder(root);
cout << endl << "The Inorder Of BST Is: " << endl;
inorder(root);
cout << endl << "The Postorder Of BST Is: " << endl;
postorder(root);
return 0;
}
Steps Of the Program:ย
- Here, the entire structure of the Nodes & the Tree will be the same as the earlier.
- We will use the same Preorder Function to print the BST in the Preorder Manner.
- Now, in the Inorder() Function, as per the rule, we will put the Left Tree Recursion first. Then, the Printing of the Node will be done. Later, the Recursion of the Right Tree will happen.
- For the Postorder() Function, we will first place the Left Tree Recursion, later the Right Tree Recursion & at the end, the printing of the Node value will be done.
Output:ย
From the above output, we can see that three different Traversal Modes are getting printed on the screen. You can notice, that Node 1 is placed at the Beginning for Preorder, in the Middle for Inorder & at last for Postorder. That means the Node 1 is the Main Root Node.
How To Search Elements In Binary Search Tree?
Now that we have come to know the Implementation Process of the Binary Search Tree, we are moving ahead in our discussion where the Search Operation on the Binary Search Tree will be discussed. You have to search for any element in BST using the Properties.
The following three steps you need to follow on any BST to find any particular element on the BST.
- Compare the Element with the Root Node & check whether they are similar or not.
- If the Element is less than the Root Node, go for the Left Subtree & check similarly.
- If the Element is higher than the Root Node, go for the Right Subtree & check similarly.
Program In CPP To Understand The Searching Process In BST:
#include
#include
using namespace std;
// Constructing The Tree
struct Node{
int data;
struct Node *left;
struct Node *right;
Node(int val){
data=val;
// Assigning the left and right nodes NULL
left=NULL;
right=NULL;
}
};
// Function To Implement BST
Node* sortedBST(int arr[],int start , int end){
if(start>end)
return NULL;
// Assinging The Mid Value
int mid = (start+end)/2;
// Assinging The Mid Value As Root Node
Node* root = new Node(arr[mid]);
// Construct Left & Right Subtree
root->left = sortedBST(arr, start, mid-1);
root->right = sortedBST(arr, mid+1 , end);
return root;
}
// Search Operation
void search(Node* root, int key)
{
// Base Cases
if (root == NULL || root->data == key){
cout<< "The Key " << key << " Is Found";
return;
}
// When Key Is Greater Than Key
if (root->data < key)
return search(root->right, key);
// When Key Is Greater Than Key
return search(root->left, key);
}
int main()
{
// Assinging The Array.
int arr[] ={3,2,1,7,9};
int len = sizeof(arr)/sizeof(int);
// Function Calling
Node *root = sortedBST(arr,0,len-1);
// Printing The Data In Preorder
search(root, 2);
return 0;
}
Steps Of The Program:ย
- The Complete Process will be identical to what we have done previously for the Insertion Process.
- Here, the New Module will be the Search Module where the Root Node & the Key Element will be accessed.
- We have implemented the above logic there. If the Element is found at the Root, the message will be printed.
- For the Lower Value, the Left Subtree will be called in the Recursive Manner.
- For the Higher Value, the Right Subtree will be called in the same Recursive Manner.
Output:ย
From the above output, we can see that Node Number 2 is found in the BST. And as Node 2 is present in the BST, the Success Message is coming as the Output. So, the C++ Code is executed successfully.
If youโre interested to know the process of implementingย BST in Java you can check out our article.
How To Delete Nodes In Binary Search Trees?
After discussing the process of finding Nodes in BST, it is time to discuss the process of deleting any node in the BST. However, there is a separate concept present to delete any element from the BST. According to that policy, we will delete Nodes.
Till the discussion, one thing should become clear to you, there are Three Scenarios of Nodes. Any Node should be Single with no Child, Any Node can have only One Child & Node have Two Children. Based on these three scenarios, we can delete the Nodes.
Scenario 1: Nodes Having No Child:ย
In this case, if you want to delete any Node that has no child bound, then go ahead & delete the node as it is a very simple process to delete. There will be no other changes in the BST in that case.
Scenario 2: Nodes Having One Child:ย
If you want to delete any Node that has only one child, then you have to just place the Child as the New Node Value in the deleted position.
Scenario 3: Nodes Having Two Children:
If you want to delete any Node that has two children, you have to follow different cases based on the Subtree where the Nodes are placed.
- If you want to Delete any Node on the Left Subtree, the immediate Left Node of the Deleted Node will get the Place.
- If you want to Delete any Node on the Right Subtree, the immediate Right Node of the Deleted Node will get the Place.
Program To Implement Delete Operation On BST Using C++ Language:
#include
#include
using namespace std;
// Constructing The Tree
struct Node{
int data;
struct Node *left;
struct Node *right;
Node(int val){
data=val;
// Assigning the left and right nodes NULL
left=NULL;
right=NULL;
}
};
// Function To Implement BST
Node* sortedBST(int arr[],int start , int end){
if(start>end)
return NULL;
// Assinging The Mid Value
int mid = (start+end)/2;
// Assinging The Mid Value As Root Node
Node* root = new Node(arr[mid]);
// Construct Left & Right Subtree
root->left = sortedBST(arr, start, mid-1);
root->right = sortedBST(arr, mid+1 , end);
return root;
}
// Function To Return Minimum Value
Node* min(Node* node)
{
Node* a = node;
while (a && a->left != NULL) // Loop To Find Left Leaf
a = a->left;
return a;
}
// Function To Delete Node
Node* dNode(Node* root, int key)
{
if (root == NULL) // Exit Case
return root;
if (key < root->data) { // If Element Smaller Than Root
root->left = dNode(root->left, key);
}
else if (key > root->data) { // If Element Higher Than Root
root->right = dNode(root->right, key);
}
else {
if (root->left == NULL) { // For Node With No CLild
Node* z = root->right;
free(root);
return z;
}
else if (root->right == NULL) { // For Node With One CLild
Node* z = root->left;
free(root);
return z;
}
Node* t = min(root->right); // For Node With Two CLildren
root->data = t->data;
root->right = dNode(root->right, t->data);
}
return root;
}
// Function To Print Pre-Order Traversal
void preorder(Node* root){
if(root==NULL)
return;
// Following The N-L-R Rule
cout<data<<" ";
preorder(root->left);
preorder(root->right);
}
int main()
{
// Assinging The Array.
int arr[] ={3,2,1,7,9};
int len = sizeof(arr)/sizeof(int);
// Function Calling
Node *root = sortedBST(arr,0,len-1);
// Printing The Data In Preorder
Node *root1 = dNode(root,1);
cout << "The New BST Is: " << endl;
preorder(root);
return 0;
}
Steps Of The Program:ย
- Here, the complete program structure will be the same just like the two previous examples.
- Here, we will include two different functions for the Delete Operation.
- In the Main Function, after the Node is created, the dNode() Function will be called along with the Node Value.
- Now, according to the above concept, the Node will be found out. Based upon the Node Condition, any one of the Conditional Statements will be used.
- If there are two Children present, then we have to find out the Minimum to swap the position.
- At last, we will again use the Preorder Traversal to get the latest BST.
Output:ย
From the Above Output, we can see that Node Number 1 is not present in the result. That means we have successfully deleted Node 1 from the BST. And the Tree Modification is done again that is the reason, we have got all the data intact.
Time Complexity & Space Complexity Of Binary Search Tree Operations:
Now at the end of the discussion, we would like to put some light on the Time & Space Complexity of the BST. Now, as the BST is only one concept & we can only perform some operations there, we can only derive the Time & Space complexity of them.
Let us start with the Time Complexity first. The Best Time Complexity of Insertion, Searching & Deletion Operations will be the O(log N). Whereas, the Worst Case Time Complexity will be the O(N). This is the pattern that is followed by every operation.
Now, if we discuss the Space Complexity, we will find the Space Complexity will be the O(N) for all of the cases. This is certain & will not change with different code snippets.
What Are Some Optimization Techniques In Binary Search Tree?
In the Binary Search Tree, there are some Optimization Techniques that you should follow. However, optimization can only be done when you are going to deal with some advanced BST. In most cases, you have to use the Optimization in the Corporate or for Large Projects.
Optimization will help to check any large or complicated operation within a very short time. And if you can optimize any large BST, your code will be the best that can handle complex problems. Here are some tips that you can implement on the BST.
- Make a BST a balanced one. Donโt make any BST where the Left Subtree or Right Subtree is larger than the other parts.
- While deleting the Nodes in the BST, make sure you have removed the Pointer from the Code to free up the space.
- If some nodes have the same kind of data, try to Reuse It as nobody is going to visualize the tree.
- The best way to optimize any BST is to reduce the Height or Depth of the Tree. The deeper the tree, the more time takes to work on it.
- Always try to use the Inorder Traversal Method to print the data in the BST. As the Inorder Traversal takes relatively less time to print any BST.
What Are Some Applications Of Binary Search Tree?
At the end of the discussion, we will conclude with some applications where the BST is highly used. From Database to Algorithm, the use of the Binary Search Tree is very vast. Let us check some of the applications one by one to get deeper insights.
- If you want to do Multilevel Indexing on the Database, then the BST will be the perfect choice.
- Different Searching Algorithms can be effectively implemented using the BST.
- If you want, the BST can also be converted to the Expression Tree.
- BST can store data for Online Platforms that can be accessed easily.
- The BST can be used for Dynamic Sorting without any issues.
- The BST will be the best choice to Manage Virtual Memory on any Operating System.
Conclusion:
As we saw, โBST in C++โ is very important.
We should clear the basics of recursion & function calling for implementing BST in C++.
We should clear the What Is BST in Data Structures. As well as we need to clear the basics. That is very important while implementing BST in C++.
So, hope you have liked this piece of article. Share your thoughts in the comments section and let us know if we can improve more.
Codingzap also offers a wide range ofย programming and codingย help services for you to benefit from. Donโt miss out!ย
Key Takeaways:ย
- BST follows a particular rule where all the lower numbers will get stored in the Left Subtree.
- All the Higher Values of the Root Node will be kept on the Right Side.
- On the Binary Search Tree, three kinds of Operations can be done, Insertion, Searching & Deletion.
- For Searching any element, we have it first check it on the Root Node respective.
- Based upon the Node Condition, the Deletion of BST can be performed.
- The Case Time Complexity of BST will be the O(log N).
- The Space Complexity will be the O(N).