You are on page 1of 6

Write a program to implement Binary tree.

OR
Write a program to insert and delete nodes in a binary tree.

#include <iostream>
using namespace std;

struct node
{
int n;
node *left;
node *right;
};
class bst
{
private:
node *start,*temp,*parent,*cur, *stack[10];
int top;
public:
bst()
{start=NULL;}
void create(int);
void gotoxy(int, int);
void displayTree();
void insertNode(int); //insert 4
// void displayTree();
void inorder();
void deleteLefyNode(node* , int); //delete 12
void delete_node();
void display_tree_inOrder();
void push(node *);
};
bst b;
void bst::gotoxy(int col, int row)
{
// col=40;
// row=1;
}
void bst::create(int data)
{
int col=40, row=1;
if(start==NULL)
{
start=new node;
start->n=data;
start->left=start->right=NULL;
gotoxy(col,row);
cout<<data<<" ";
// cout<<endl;
}
else
{
node *parent;
cur=start;
while(cur!=NULL)
{
if(cur->n==data)
{
cout<<"Data already exist\n";
return;
}
if(cur->n<data)
{
parent=cur;
cur=cur->right;
row+=2;
col+=6;
}
else
{
parent=cur;
cur=cur->left;
row+=2;
col-=6;
}
}
temp=new node;
temp->n=data;
temp->left=temp->right=NULL;
gotoxy(col,row);
cout<<data<<" ";
// cout<<endl;
if(parent==NULL)
{
parent=temp;
}
else if(parent->n>data)
{
parent->left=temp;
}
else
{
parent->right=temp;
}
}
}
void bst::insertNode(int data)
{
if(start==NULL)
{
start=new node;
start->n=data;
start->left=start->right=NULL;
}
else
{
cur=start;
while(cur!=NULL)
{
if(cur->n==data)
{
return;
}
if(cur->n<data)
{
parent=cur;
cur=cur->right;
}
else
{
parent=cur;
cur=cur->left;
}
}
temp=new node;
temp->n=data;
temp->left=temp->right=NULL;
if(parent==NULL)
{
parent=temp;
}
else if(parent=temp)
{
parent->left=temp;
}
else
{
parent->right=temp;
}
}
}
void bst::delete_node()
{
int val;
cout<<"\nValue of leaf node to delete is: ";
cin>>val;
b.deleteLefyNode(start, val);
}
void bst::deleteLefyNode(node *ds, int data)
{
if(ds==NULL)
{
cout<<"Tree is empty: ";
return;
}
else
{
cur=parent=ds;
while(cur!=NULL)
{
if(cur->n==data)
{
if(cur->left==NULL && cur->right==NULL)
{
break;
}
}
if(cur->n<data)
{
parent=cur;
cur=cur->right;
}
else
{
parent=cur;
cur=cur->left;
}
}
if(cur==NULL)
{
cout<<"Leaf node not found: \n";
return;
}
}
if(data>parent->n)
{
parent->right=NULL;
}
else
{
parent->left=NULL;
}
cout<<"\nData of tree in inorder after deleting the node\n";
b.inorder();
}
void bst::display_tree_inOrder()
{
if(start==NULL)
{
cout<<"Tree is empty:\n";
return;
}
else
{
cout<<endl<<endl;
cout<<"Traversal in inorder\n";
cur=start;
push(cur);
cout<<endl;
while(top>=0)
{
cur=stack[top];
top--;
cout<<cur->n<<"\t";
if(cur->right!=NULL)
{
push(cur->right);
}
}
}
}
void bst::push(node *cc)
{
while(cc!=NULL)
{
top++;
stack[top]=cc;
cc=cc->left;
}
}
int main()
{
int x[]={10,13,8,12,17,7,9,6};
for(int i=0; i<=7; i++)
{
b.create(x[i]);
}
b.insertNode(4);
b.delete_node();
}

You might also like