BST Insert Delete Display
BST Insert Delete Display
Source code
#include <iostream>
using namespace std;
struct node {
int key;
struct node *left, *right;
};
//creation
struct node *newNode(int item)
{
struct node *temp = new node;
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}
//traversal
void inorder(struct node *root)
{
if (root != NULL)
{
inorder(root->left);
cout << root->key << " ";
inorder(root->right);
}
}
void preorder(struct node* root)
{
if(root!=NULL)
{
cout<<root->key<<" ";
preorder(root->left);
preorder(root->right);
}
}
return node;
}
// inorder successor
struct node *minValueNode(struct node *node)
{
struct node *current = node;
while (current && current->left != NULL)
current = current->left;
return current;
}
// Deleting a node
struct node *deleteNode(struct node *root, int key)
{
if (root == NULL)
return root;
if (key < root->key)
root->left = deleteNode(root->left, key);
else if (key > root->key)
root->right = deleteNode(root->right, key);
else
{
if (root->left == NULL)
{
struct node *temp = root->right;
free(root);
return temp;
}
else if (root->right == NULL)
{
struct node *temp = root->left;
free(root);
return temp;
}
struct node *temp = minValueNode(root-
>right);
root->key = temp->key;
root->right = deleteNode(root->right, temp-
>key);
}
return root;
}
int main()
{
struct node *root = NULL;
int choice;
cout<<"enter 1 to insert"<<endl;
cout<<"enter 2 to delete"<<endl;
cout<<"enter 3 to display"<<endl;
cin>>choice;