我编了一个二叉树的非递归遍历的程序,最后结果总是出问题,请大家帮忙看看。谢!
struct bitree
{
char data;
struct bitree *lchild,*rchild;
};
struct stack
{
int i;
struct bitree *treenode;
struct stack *next;
};
push(head,binode)
struct stack *head;
struct bitree *binode;
{
struct stack *p,*q;
q=head;
while( q->next )
q=q->next;
p=(struct stack *)malloc(sizeof(struct stack));
p->next=0;
q->next=p;
p->treenode->data=binode->data;
p->treenode->lchild=binode->lchild;
p->treenode->rchild=binode->rchild;
}
struct stack *pop(head)
struct stack *head;
{
struct stack *p,*q;
if( head->next==0 )
{
printf("ERROR");
exit(0);
}
p=head;
q=head->next;
while( q->next )
{
p=q;
q=q->next;
}
p->next=0;
return q;
}
struct bitree *createbitree() /* 递归建立二叉树 */
{
struct bitree *t;
char ch;
scanf("%c",&ch);
if( ch!='#' )
{
if( ch=='0' )
t=0;
else
{
t=(struct bitree *)malloc(sizeof(struct bitree));
if( t==0 )
exit(0);
t->data=ch;
t->lchild=createbitree();
t->rchild=createbitree();
}
}
return t;
}
traverse1(t) /* 前序递归遍历 */
struct bitree *t;
{
if(t)
{
printf("%c ",t->data);
traverse1(t->lchild);
traverse1(t->rchild);
}
}
traverse2(t) /* 中序递归遍历 */
struct bitree *t;
{
if(t)
{
traverse2(t->lchild);
printf("%c ",t->data);
traverse2(t->rchild);
}
}
traverse3(t) /* 后序递归遍历 */
struct bitree *t;
{
if(t)
{
traverse3(t->lchild);
traverse3(t->rchild);
printf("%c ",t->data);
}
}
freenode(t)
struct bitree *t;
{
if(t)
{
freenode(t->lchild);
freenode(t->rchild);
free(t);
}
}
main()
{
struct bitree *t,*q;
struct stack *head,*p;
head=(struct stack *)malloc(sizeof(struct stack));
head->next=0;
printf("Please input:");
t=createbitree();
printf("\n****di gui\n");
traverse1(t);
printf("\n");
traverse2(t);
printf("\n");
traverse3(t);
printf("\n\n****fei di gui\n");
push(head,t);
while( head->next )
{
p=pop(head);
printf("%c ",p->treenode->data);
q=p->treenode->rchild;
if( q )
push(head,q);
q=p->treenode->lchild;
if( q )
push(head,q);
free(p);
}
free(head);
freenode(t);
}