Social Icons

Saturday, 27 April 2013

Preorder and Postorder Tree Implementation Using Linked List


#include<iostream>
#include<string.h>
#include<conio.h>
#include<stdio.h>
using namespace std;
int top=0;
struct node
{
int info;
node * right;
node * left;
}*newptr,*root,*par,*ptr,*pos,*save,*loc,*child,*parsuc,*suc,*s,*stack[10];
void ins(int);
void show();
void disp();
void view();
void find(int);
int main()
{
root=NULL;
//clrscr();
int a,item;
char ch;
int i,n;
cout<<"\n enter limit : ";
cin>>n;
cout<<"\n\n\n\tEnter the item to insert: ";
for(i=0;i<n;i++)
{ cin>>a;
ins(a);
}
stack[top]=NULL;
               
cout<<"\n\t Pre-order of tree :\t";
disp();
cout<<"\n\t In-order of tree :\t";
show();

getch();

}
void ins(int a)
{
newptr=new node[1];
newptr->info=a;
newptr->right=newptr->left=NULL;

if(root==NULL)
{
root=newptr;
}
else
{
ptr=root;
while(ptr!=NULL)
{
if(ptr->info>=a)
{
if(ptr->left==NULL)
{
ptr->left=newptr;
break;
}
ptr=ptr->left;
}
else
{
if(ptr->right==NULL)
{
ptr->right=newptr;
break;
}
ptr=ptr->right;
}
}
}
}
void disp()
{

ptr=root;
top=0;
while(ptr!=NULL)
{       cout<<"\t"<<ptr->info;
if(ptr->right!=NULL)
{       top++;
stack[top]=ptr->right;
}
if(ptr->left!=NULL)
{
ptr=ptr->left;
}
else
{    
ptr=stack[top--];
}

}

}

  void show()
  {
  ptr=root;
  x: while(ptr!=NULL)
  {
 
  top=top+1;
  stack[top]=ptr;
 
  ptr=ptr->left;
    }
 
    ptr=stack[top];
    top=top-1;
    while(ptr!=NULL)
    {
    cout<<"\t "<<ptr->info;
     if(ptr->right!=NULL)
        {
         ptr=ptr->right;
         goto x;
        }
 
     ptr=stack[top];
    top=top-1;
 
  }
     

    }
 











   
   
   
   
   

 

No comments:

Post a Comment

 

Sample Text

Sample text

 
Just Programming Cse DriveReputation Management