Description:This is a Program to Prevent Deletion of nodes having 0 or 1 degrees in the Binary Search Tree.
The approach will be as follow::
First, we will Construct the Binary Search Tree and insert some nodes
After Consrtucting this BST we can observe the nodes
0 Degree nodes -> 40, 75, 100, 150
1 Degree nodes -> No nodes
2 Degree nodes -> 95 55 110
So the Program is to prevent deletion of 0-degree or 1-degree nodes (i.e 40, 75, 100, 150 )
LOGIC::
we will check if the root's right child is NULL and the root's left child is NULL?
if yes then that node is having 0 degrees.
we will check if the root's right child is NULL or the root's left child is NULL?
if yes then that node is having 1 degree.
so don't perform deletion on both of these cases simply return by giving the message.
Here is the sample code for more clarification.
C++ CODE
#include <bits/stdc++.h>
using namespace std;
struct BST_node
{
int data;
struct BST_node *left, *right;
};
typedef struct BST_node node;
void in_order(node *root)
{
if (root)
{
in_order(root->left);
cout << root->data << " ";
in_order(root->right);
}
}
node *create_node(int d)
{
node *ptr = (node *)malloc(sizeof(node));
ptr->data = d;
ptr->right = ptr->left = NULL;
return ptr;
}
node *insert_node(node *root, int key)
{
if (!root)
return create_node(key);
if (key < root->data)
root->left = insert_node(root->left, key);
else
root->right = insert_node(root->right, key);
return root;
}
node *min_value(node *root)
{
node *current = root;
while (current && current->left != NULL)
current = current->left;
return current;
}
node *delete_node(node *root, int key)
{
if (!root)
return root;
if (key < root->data)
root->left = delete_node(root->left, key);
else if (key > root->data)
root->right = delete_node(root->right, key);
else
{
if (root->left == NULL)
{
cout << "\n"
<< root->data << " not having degree 2 can't delete :(" << endl;
return root;
}
else if (root->right == NULL)
{
cout << "\n"
<< root->data << " not having degree 2 can't delete :(" << endl;
return root;
}
node *temp = min_value(root->right);
root->data = temp->data;
root->right = delete_node(root->right, temp->data);
}
return root;
}
int main()
{
node *root = NULL;
root = insert_node(root, 95);
insert_node(root, 55);
insert_node(root, 40);
insert_node(root, 75);
insert_node(root, 110);
insert_node(root, 100);
insert_node(root, 150);
cout << "\nIN ORDER :: ";
in_order(root);
cout << endl;
cout << "\nDeleting 40..." << endl;
root = delete_node(root, 40);
cout << "\nIN ORDER :: ";
in_order(root);
cout << endl;
return 0;
}
Comments