Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- #include<stdlib.h>
- struct node
- {
- int data;
- struct node *left;
- struct node *right;
- };
- struct node *root=NULL;
- struct node *create(int item);
- void postorder(struct node *root);
- void preorder(struct node *root);
- int main()
- {
- struct node *root=create(11);
- root->left=create(22);
- root->right=create(33);
- root->left->left=create(44);
- root->left->right=create(55);
- root->right->left=create(66);
- root->right->right=create(77);
- printf("postorder traversal result\n");
- postorder(root);
- printf("\n");
- printf("preorder traversal result\n");
- preorder(root);
- }
- struct node *create(int item)
- {
- struct node *temp;
- temp=(struct node*)malloc(sizeof(struct node));
- temp->data=item;
- temp->left=NULL;
- temp->right=NULL;
- return temp;
- }
- void postorder(struct node *root)
- {
- struct node *stack[20],*ptr;
- int top=-1;
- ptr=root;
- while(1)
- {
- if(ptr!=NULL)
- {
- stack[++top]=ptr;
- ptr=ptr->left;
- }
- else
- {
- if(top==-1)
- break;
- else
- {
- if(stack[top]->right==NULL)
- {
- ptr=stack[top--];
- printf("%d ",ptr->data);
- while(ptr==stack[top]->right)
- {
- printf("%d ",stack[top]->data);
- ptr=stack[top--];
- if(top==-1)
- break;
- }
- }
- if(top!=-1)
- ptr=stack[top]->right;
- else
- ptr=NULL;
- }
- }
- }
- }
- void preorder(struct node *root)
- {
- struct node *ptr,*stack[20];
- int top=-1;
- ptr=root;
- while(1)
- {
- while(ptr!=NULL)
- {
- printf("%d ",ptr->data);
- stack[++top]=ptr;
- ptr=ptr->left;
- }
- if(top==-1)
- break;
- else
- {
- ptr=stack[top--];
- ptr=ptr->right;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement