二叉树的层次建立及后序遍历

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);
}


...全文
158 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
kkndciapp 2008-10-03
  • 打赏
  • 举报
回复
有几个地方括号都写错了,比如:while(!(p==NULL||top==-1)
mabo321 2008-10-03
  • 打赏
  • 举报
回复

(tree)malloc(sizeof(struct tree);

没有 free 内存泄漏~~


aozhi 2008-10-03
  • 打赏
  • 举报
回复
虽然很真诚,但代码格式太乱.
我不愿意看.
九十度黑 2008-10-03
  • 打赏
  • 举报
回复
1.scanf后加:fflush(stdin);
2.root=(tree)malloc(sizeof(struct snode));
3.申请结点后:root->lchild = root->rchild = NULL;
参考一下书,再仔细改改吧,感觉功能不对。
xjpcj 2008-10-03
  • 打赏
  • 举报
回复
那个括号有在,发帖的时候太急,没加,不好意思!至于2楼说的不懂,在创建的时候creat()函数中不能free掉的,最后遍历的时候inorder()函数的最后加free(qt[top);还是不行。不知道是不是俺的电脑有问题,呵呵!

69,373

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧