pre_order traversal using stack in c
I am not able to figure out why the program is printing only first 3 characters of the tree. Please help.
#include <stdio.h>
#includ开发者_JAVA百科e <malloc.h>
struct node
{
struct node *left;
char data;
struct node *right;
};
struct node *buildtree(int);
void pre_order(struct node*);
char a[]={'a','b','c','d','e','f','g','\0','\0','h','\0','\0','\0','\0','\0','\0','\0','\0','\0','\0','\0'};
int main()
{
struct node *root;
root = buildtree(0);
printf("pre order traversal:\n");
pre_order(root);
}
struct node *buildtree(int n)
{
struct node *temp = NULL;
if(a[n]!='\0')
{
temp=(struct node*)malloc(sizeof(struct node));
temp->left=buildtree(2*n+1);
temp->data=a[n];
temp->right=(2*n+2);
}
return temp;
}
void pre_order(struct node* root)
{
char stack[30];
struct node* ptr;
int top=1;
stack[1]=NULL;
ptr=root;
while(ptr!=NULL)
{
printf("%c",ptr->data);
if(ptr->right!=NULL)
{
top=top+1;
stack[top]=ptr->right;
}
if(ptr->left!=NULL)
ptr=ptr->left;
else
{
ptr=stack[top];
top=top-1;
}
}
}
I'm surprised that compiled
char stack[30];
should be replaced by
struct node* stack[30];
There might be other problems.
You wrote a nice recursive routine to build the tree, why not write a recursive routine to do a pre-order traversal. It would be much easier to understand.
Simply calling something "stack" won't make it behave as one. When you push something onto a stack, the existing values get pushed down, and the reverse is true for popping.
I'd start with a working stack implementation, preferably with own functions for pushing and popping stuff.
精彩评论