Here you will find solutions of many problems on spoj. If you want solution of some problem which is not listed in blog or have doubt regarding any spoj problem (which i have solved) or any programming concept (data structure) you can mail me @ raj.nishant360@gmail.com

And my humble request to you all that don't copy the code only try to understand the logic and algorithm behind the code. I have started this because if you tried as hard as you can and still can't find any solution to the problem then you can refer to this.
You can read my answer how to start competitive programming CLICK HERE

Monday, December 23, 2013

postorder traversal using stack

postorder traversal
here the c code for postorder traversal using stack.

Was this help full if not then comment your views to improve my blog or you can mail me @ raj.nishant360@gmail.com
#include<stdio.h>
#include<stdlib.h>
struct node
{
 int data;
 struct node *LCHILD;
 struct node *RCHILD;
}*tree;
struct stack
{
 struct node *addr[100];
 int top;
}s,s1,s2;
void push(struct node *val,struct stack *temp)
{
 if(temp->top==99)
 {
  printf("overflow\n");
  return ;
 }
 temp->addr[++temp->top]=val;
}
struct node *pop(struct stack *temp)
{
 if(temp->top==-1)
 {
  printf("under flow\n");
  return NULL;
 }
 return temp->addr[temp->top--];
}
struct node *peep(struct stack * temp)
{
 if(temp->top==-1)
  return NULL;
 return temp->addr[temp->top];
}
struct node *create(int val)
{
 struct node *temp;
 temp=(struct node*)malloc(sizeof(struct node));
 temp->data=val;
 temp->LCHILD=NULL;
 temp->RCHILD=NULL;
 return temp;
}
void add(struct node **tr,int val)
{
 struct node *copy,*copy1;
 copy=(struct node*)malloc(sizeof(struct node));
 copy1=(struct node*)malloc(sizeof(struct node));
 copy1=*tr;
 if(copy1==NULL)
 {
  *tr=create(val);
  return ;
 }
 if(val>=copy1->data)
  add(&(copy1->RCHILD),val);
 else
  add(&(copy1->LCHILD),val);
}
void print_postorder(struct node *root)
{
 if(root==NULL)
  return;
 do
 {
  while(root!=NULL)
  {
   if(root->RCHILD!=NULL)
    push(root->RCHILD,&s2);
   push(root,&s2);
   root=root->LCHILD;
  }
  root=pop(&s2);
  if(root->RCHILD!=NULL && root->RCHILD==peep(&s2))
  {
   pop(&s2);
   push(root,&s2);
   root=root->RCHILD;
  }
  else
  {
   printf("%d\t",root->data);
   root=NULL;
  }
 }while(s2.top!=-1);
}
int main()
{
 tree=NULL;
 s.top=-1;
 s1.top=-1;
 s2.top=-1;
REPEAT:
 printf("ENTER YOUR CHOICE\n");
 printf("1->add node to tree\n");
 printf("2->print in INORDER tree\n");
        printf("3->exit\n");
 int choice,val;
 scanf("%d",&choice);
 switch(choice)
 {
 case 1:
  scanf("%d",&val);
  add(&tree,val);
  break;
 case 2:
  print_postorder(tree);
  break;
 case 3:
  exit(2);
 default:
  printf("your choice is incorrect\n");
 }
 goto REPEAT;
 return 0;
}

No comments:

Post a Comment

Your comment is valuable to us