Saturday, 16 March 2019

Program of Trees in C++ language

#include<iostream>
#include<conio.h>
using namespace std;

struct node{
int data;
node *left=NULL;
node *right=NULL;
};

class tree{
private:
node *root=NULL;
public:
void insert(int value);
std
};

void tree::insert(int value){
node *temp = new node;
temp->data = value;
if(root == NULL){
root = temp;
cout<<"\n**Root Inserted**\n";
}else{
node *current = root; // holds the address of nodes from root
node *ptr = NULL; //temporary pointer which hold the address of left/right node which is null
while(current != NULL){
ptr = current; //assigning the address of current node
if(value > current->data){
current=current->right;
}else if(value< current->data){
current = current->left;
}else{
cout<<"\n***Data already exist***\n";
return;
}
} // while ends here
if(value < ptr->data){
ptr->left = temp;
cout<<"Data inserted at Left after "<<ptr->data<<endl;
}else{
ptr->right = temp;
cout<<"Data inserted at Right after "<<ptr->data<<endl;
}
} // outer else ends here
}
int main(){
tree t1;
char c;
do{
int data;
cout<<"\n=======New Data==============\n\n";
cout<<"Enter data : ";
cin>>data;
t1.insert(data);
cout<<"\nDo you want to run this program again?(y/n) : ";
cin>>c;
}while(c=='y'||c=='Y');
getch();
}

output:



Share: