Here , I'll give some examples of C++ which is very much useful in programming.
Here is the code to make tree in c++.
#include <iostream>
using namespace std;
class linklist
{
typedef struct node
{
int info;
node *lchild;
node *rchild;
}node;
node *root;
public:
linklist()
{ root = 0; }
void insert(int d)
{
node * temp = new node;
temp->info = d;
temp->lchild = 0;
temp->rchild = 0;
if (root == 0)
{
root = temp;
}
else
{ node *t,*p= root;
t = p;
while (t && t->info != d)
{ p = t;
if ( d < t->info ) t = t->lchild;
else t = t->rchild;
}
if (d == p->info) {cout<<"\nDuplicate Node\n"; return;}
else if (d < p->info) p->lchild = temp;
else p->rchild = temp;
}
return;
}
void inorder(node* ch)
{
if (ch == 0) return;
inorder(ch->lchild);
cout<<ch->info<<" ";
inorder(ch->rchild);
return;
}
void postorder(node* ch)
{
if (ch == 0) return;
inorder(ch->lchild);
inorder(ch->rchild);
cout<<ch->info<<" ";
return;
}
void preorder(node* ch)
{
if (ch == 0) return;
cout<<ch->info<<" ";
inorder(ch->lchild);
inorder(ch->rchild);
return;
}
void traverse()
{
cout<<endl<<endl<<"1. Preorder" ;
cout<<endl<<"2. Inorder";
cout<<endl<<"3. Postorder";
// cout<<endl<<"4. Exit"<<endl;
char ch;
cin>>ch;
switch(ch)
{
case '1':
preorder(root);break;
case '2':
inorder(root);break;
case '3':
postorder(root);break;
}
}
void remove(int d)
{
node *t,*p = root;
t = p;
bool found = false;
while(t)
{
if (d == t->info){found = true; break;}
p = t;
if (d< t->info) t= t->lchild;
else t= t->rchild;
}
if (found)
{
if(t->lchild == 0)
{
if(d < p->info)
p->lchild = t->rchild;
else
p->rchild = t->rchild;
}
else if(t->rchild == 0)
{
if(d < p->info)
p->lchild = t->lchild;
else
p->rchild = t->lchild;
}
else if( t->rchild !=0 && t->lchild !=0)
{
if(d < p->info)
p->lchild = t->lchild;
else
p->rchild = t->lchild;
node* q, *r;
r = t->lchild;
while(r)
{
q = r;
r = r->rchild;
}
q->rchild= t->rchild;
}
delete(t);
}
else cout<<"\n\nNot found\n";
}
};
int main()
{
bool loop =1;
linklist t;
while (loop)
{
cout<<endl<<endl<<"1. insert" ;
cout<<endl<<"2. traverse";
cout<<endl<<"3. delete";
cout<<endl<<"4. Exit"<<endl;
char ch;
cin>>ch;
switch(ch)
{
case '1':
cout<<endl<<"Enter a number :";
int d;
cin>>d;
t.insert(d);
break;
case '2':
t.traverse();
break;
case '3':
cout<<endl<<"Enter a number :";
int m;
cin>>m;
t.remove(m);
break;
case '4':
loop=0;
}
}
}