Inorder preorder traversal using stack..
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node* left;
struct node* right;
};
struct node* newNode(int data)
{
struct node* node = (struct node*)malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
struct stack
{
int top;
struct node *stacktop[100];
}*stack=NULL;
bool push(struct node* naya)
{
if(stack==NULL)
{
stack=(struct stack *)malloc(sizeof(struct stack ));
stack->top=0;
}
return stack->stacktop[stack->top++]=naya;
}
struct node *pop()
{
if(stack->stacktop)
{
return stack->stacktop[--stack->top];
}
return NULL;
};
void preorder(struct node *head)
{
while((stack&&stack->top)||head)
{
while(head)
{
printf("%d ",head->data);
push(head);
head=head->left;
}
if(head=pop())
{
head=head->right;
}
}
}
void printInorder(struct node *current)
{
while((stack&&stack->top)||current)
{
while(current)
{
push(current);
current=current->left;
}
if(current=pop())
{
printf("%d ",current->data);
current =current ->right;
}
}
}
int main()
{
/* Constructed binary tree is
1
/ \
2 3
/ \
4 5
*/
struct node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
printf("Inorder traversal of the original tree is \n");
printPreorder(root);
printf("\nInorder traversal of the original tree is \n");
printInorder(root);
getchar();
return 0;
}
Comments
Post a Comment