草鸡蛋 土鸡蛋 洋鸡蛋:二叉树的存储与遍历问题 我的程序有两个错误帮我找一下

来源:百度文库 编辑:神马品牌网 时间:2024/05/10 11:54:16
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define NULL 0
#define N 10
typedef struct treenode {
int data;
struct treenode *lchild,*rchild;
}TREENODE,*TREENODEPTR,*BTREE;
void CreateTree(BTREE *root){
int value,front,rear;
TREENODEPTR t,q[N];
scanf("%D",&value);
if(value==0){*root=NULL;return;};
*root=(TREENODEPTR)malloc(sizeof(TREENODE));
(*root)->data=value;
rear=front=1;
q[front]=*root;
while(front<=rear){
t=q[front];
front++;
scanf("%d",&value);
if(value==0){*root=NULL;return;};
*root=(TREENODEPTR)malloc(sizeof(TREENODEPTR));
(*root)->data=value;
rear=front=1;
q[front]=*root;
while(front<=rear){
t=q[front];
front++;
scanf("%d",&value);
if(value==0){t->lchild=NULL;}
else{
t->lchild=(TREENODEPTR)malloc(sizeof(TREENODE));
t->lchild->data=value;
rear++;
q[rear]=t->lchild;
}
scanf("%d",&value);
}
if(value==0){t->rchild=NULL;}
else{
t->rchild=(TREENODEPTR)malloc(sizeof(TREENODE));
t->rchild->data=value;
rear++;
q[rear]=t->rchild;
}
}
}
void PreOrder(BTREE root){
TREENODEPTR p,s[N];
int top=0;
p=root;
while(1){
while(p!=NULL){
printf("%d",p->data);top++;s[top]=p;p=p->lchild;}
if(top!=0){
p=s[top];top--;p=p->rchild;
}else return;
}
void InOrder(BTREE root)
{TREENODEPTR p,s[N];
int top=0;
p=root;
while(1){
while(p!=NULL){
top++;s[top]=p;p=p->lchild;
}
if(top!=0){
p=s[top];printf("%d",p->data);top--;p=p->rchild;
}else return;
}

void PostOrder(BTREE root){
TREENODEPTR p,s[N];
int top=0;
while(1){
while(p!=NULL){
top++;s[top]->rchild!=NULL){
p=s[top]->rchild;break;
}
while(top!=0&&(s[top]->rchild==NULL||p==s[top]->rchild)){
p=s[top];top--;printf("%d",p->data);
}
if(top==0)return;
}
}
}
void LayerOrder(BTREE root){
TREENODEPTR p,s[N];
int top,bottom,m,n;
p=root;top=1;s[top]=p;
bottom=top;
while(1){
n=bottom;
m=top;
bottom=top+1;
while(m>=n){
p=s[m];
m--;
if(p->lchild!=NULL){top++;s[top]=p->rchild;}
}
if(top==bottom-1)break;
n=bottom;m=top;
bottom=top+1;
while(m>=n){
p=s[m];
m--;
if(p->lchild!=NULL){top++;s[top]=p->lchild;}
}
if(top==bottom-1)break;
}
while(top>=1){printf("%d",s[top]->data);top--;}
printf("\n");
}
void main()
{ BTREE root;
CreateTree(&root);
printf("\nPreOrderTravPath:");PreOrder(root);
printf("\n\nInOrderTravPath:");InOrder(root);
printf("\n\nPostOrderTravPath:");PostOrder(root);
printf("\n\n\nLayerOrderTravPath:");LayerOrder(root);
printf("\n");
}
}