二叉树的层次建立及后序遍历
xjpcj 2008-10-03 11:48:11 能运行,但结果出错,虽然分数不多,但小弟我很真诚,哪位高手能告诉我吗?
#include<stdio.h>
#define max 10
typedef struct node{
char ch;
struct node *lchild;
struct node *rchild;
}*tree;
typedef struct snode
{tree st;
int flag;
}stack;
tree creat()
{tree root ,bt,queue[max];
int front=-1,rear=-1;
char x;
scanf("%c",&x);
if(x=='0')return NULL;
root=(tree)malloc(sizeof(tree);
root->ch=x;
rear++;
queue[rear]=root;
while(x!='f')
{front++;
bt=queue[front];
scanf("%c",&x);
if(x=='0')bt->lchild=NULL;
bt->lchild=(tree )malloc(sizeof(tree));
bt->lchild->ch=x;
rear++;
queue[rear]=bt->lchild;
scanf("%c",&x);
if(x=='0')bt->rchild=NULL;
bt->rchild=(tree)malloc(sizeof(tree));
bt->rchild->ch=x;
rear++;
queue[rear]=bt->rchild;
}
return root;}
void inorder(tree bt)
{stack qt[max];
int top,sign;
tree p;
top=-1,sign=0;
p=bt;
while(!(p==NULL||top==-1)
{if(p!=NULL)
{top++;
qt[top].st=(tree)malloc(sizeof(tree));
qt[top].flag=(int)malloc(sizeof(int));
qt[top].st=p;
qt[top].flag=1;
p=p->lchild;
}
else
{p=qt[top].st;
sign=qt[top].flag;
top--;
if(sign==1)
{top++;
qt[top].st=p;
qt[top].flag=2;
p=p->rchild;}
else
{printf("%c",p->ch);
p=NULL;
}
}
}
}
main()
{tree root;
root=creat();
inorder(root);
}