Here is my function for iterative inorder traversal. But when I execute it I'm getting a segmentation fault. I'm using a stack for the traversal. In the given program I also have a recursive function for inorder traversal to check if my create() function is working.
I'm pushing the node to the stack and moving to the left of the node and after that I'm popping the node from the stack and printing it and going to the right by doing
root=root->rlink
.
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node *llink;
struct node *rlink;
}Node;
typedef struct Stack
{
Node *a[10];
int top;
}stack;
void push(stack *s,Node *root)
{
if(s->top==9)
printf("FULL");
else
{
s->top++;
s->a[s->top]=root;
}
}
Node *pop(stack *s)
{
if(s->top==-1)
printf("Empty");
return s->a[s->top--];
}
void inorder(Node *root)
{
stack s;
s.top=-1;
int flag=1;
while(flag)
{
if(s.top!=9)
{
push(&s,root);
root=root->llink;
}
else{
if(s.top!=-1)
{
root=pop(&s);
printf("%d",root->data);
root=root->rlink;
}
else
flag=0;
}
}
}
void inor(Node *root)
{
if(root!=NULL)
{
inor(root->llink);
printf("%d",root->data);
inor(root->rlink);
}
}
Node *create(Node *root,int key)
{
if(root==NULL)
{
root=(Node *)malloc(sizeof(Node));
root->data=key;
root->rlink=root->llink=NULL;
}
else
{
if(key>root->data)
{
root->rlink=create(root->rlink,key);
}
else if(key<root->data)
{
root->llink=create(root->llink,key);
}
}
return root;
}
int main()
{
Node *h=NULL;
h=create(h,5);
h=create(h,1);
h=create(h,3);
h=create(h,8);
h=create(h,12);
h=create(h,51);
inorder(h);
//inor(h);
}
fflush(stdout);
) — otherwise, you may never see the message if the code crashes, giving you the wrong impression about where the crash occurs. – Jonathan Leffler