Tuesday, November 22, 2011

7 Binary Transversal

Preorder Inorder Postorder (Using RECURSION)


#include<iostream>
#include<cmath>

using namespace std;

void getdata();
void inorder(int);
void preorder(int);
void postorder(int);

int t[50];
int n,i,l;

int main()
{
getdata();

cout<<"\nINORDER";
inorder(1);

cout<<"\nPREORDER";
preorder(1);

cout<<"\nPOSTORDER";
postorder(1);
cout<<"\n";

return 0;

}

void getdata()
 {
 cout<<"\nEnter the no.of levels of the binary tree:";
 cin>>l;

 n=(pow(2,l))-1;
 cout<<"\nThe maximum no.of the nodes for the given level of the binary tree is"<<" "<<n<<"\n";
 cout<<"\nEnter the nodes of the tree:";
 for(i=1;i<=n;i++)
 cin>>t[i];
 }

 void inorder(int i)
 {
  if(i<=n)
  {
  inorder(i*2);
  if(t[i]!=0)
  cout<<"\t"<<t[i];
  inorder(i*2+1);
  }
 }

 void preorder(int i)
 {
  if(i<=n)
  {
  if(t[i]!=0)
  cout<<"\t"<<t[i];
  preorder(i*2);
  preorder(i*2+1);
  }
 }

 void postorder(int i)
 {
  if(i<=n)
  {
  postorder(i*2);
  postorder(i*2+1);
  if(t[i]!=0)
  cout<<"\t"<<t[i];
  }
 }

No comments:

Post a Comment