Data Structures
Data Structures
Data Structures
Algorithm:
Insertion-
1. Create a new BST node and assign values to it.
2. insert(node, key)
if root == NULL,
return the new node to the calling function.
if root=>data < key
call the insert function with root=>right and assign the return value in root=>right.
root->right = insert(root=>right,key)
if root=>data > key
call the insert function with root->left and assign the return value in root=>left.
root=>left = insert(root=>left,key)
3. Finally, return the original root pointer to the calling function.
Deletion-
1.Leaf Node
If the node is leaf (both left and right will be NULL), remove the node directly and free its
memory.
2. Node with Right Child
If the node has only right child (left will be NULL), make the node points to the right node and
free the node.
3. Node with Left Child
If the node has only left child (right will be NULL), make the node points to the left node and free
the node.
4. Node has both left and right child
If the node has both left and right child,
find the smallest node in the right subtree. say min
make node->data = min
Again delete the min node.
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
Program code:
#include <iostream>
using namespace std;
struct Node {
int data;
Node *left;
Node *right;
};
Node* create(int item)
{
Node* node= new Node;
node->data = item;
node->left = node->right = NULL;
return node;
}
void inorder(Node *root)
{
if (root == NULL)
return;
inorder(root->left);
cout<< root->data << " ";
inorder(root->right);
}
Node* findMinimum(Node* cur)
{
while(cur->left != NULL)
{cur = cur->left;
}
return cur;
}
Node* insertion(Node* root, int item)
{
if (root == NULL)
return create(item);
if (item < root->data)
root->left = insertion(root->left, item);
else
root->right = insertion(root->right, item);
return root;
}
void search(Node* &cur, int item, Node* &parent)
{
while (cur != NULL && cur->data != item)
{
parent = cur;
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
}
}
int main()
{
Node* root = NULL;
root = insertion(root, 3);
root = insertion(root, 2);
root = insertion(root, 5);
root = insertion(root, 7);
root = insertion(root, 9);
root = insertion(root, 8);
root = insertion(root, 6);
root = insertion(root, 4);
printf("The inorder traversal of the given binary tree is - \n");
inorder(root);
deletion(root, 9);
printf("\nAfter deleting node 9, the inorder traversal of the given binary tree is - \n");
inorder(root);
insertion(root, 1);
printf("\nAfter inserting node 1, the inorder traversal of the given binary tree is - \n");
inorder(root);
return 0;
}
Output: