数据结构程序设计 先序遍历二叉树的递归或非递归算法 用C或C++

像是三千字那种实验报告

#include<stdio.h>
struct node
{int data;
struct node *lch;
struct node *rch;};
typedef struct node bitree;
bitree *creat()
{bitree *t;
int x;
scanf("%d",&x);
if(x==0) t=NULL;
else
{t=(bitree*)malloc(sizeof(bitree));
t->data=x;
t->lch=creat();
t->rch=creat();}
return t;}
void preorder(bitree * b)
{bitree *p;
bitree *stack[10];
int top=-1;
if (b!=NULL)
{top=top+1;
stack[top]=b;
while(top>-1)
{p=stack[top];
top=top-1;
printf("%d",p->data);
if(p->rch!=NULL)
{top=top+1;
stack[top]=p->rch;}
if(p->lch!=NULL)
{top=top+1;
stack[top]=p->lch;}
}
printf("\n");}
}
main()
{bitree *b;
b=creat();
preorder(b);
getch();
}追问

有错误

追答

我这显示没有啊

温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-03-14
#include<stdio.h>
struct node
{int data;
struct node *lch;
struct node *rch;};
typedef struct node bitree;
bitree *creat()
{bitree *t;
int x;
scanf("%d",&x);
if(x==0) t=NULL;
else
{t=(bitree*)malloc(sizeof(bitree));
t->data=x;
t->lch=creat();
t->rch=creat();}
return t;}
void preorder(bitree * b)
{bitree *p;
bitree *stack[10];
int top=-1;
if (b!=NULL)
{top=top+1;
stack[top]=b;
while(top>-1)
{p=stack[top];
top=top-1;
printf("%d",p->data);
if(p->rch!=NULL)
{top=top+1;
stack[top]=p->rch;}
if(p->lch!=NULL)
{top=top+1;
stack[top]=p->lch;}
}
printf("\n");}
}
main()
{bitree *b;
b=creat();
preorder(b);
getch();
}追问

运行不了 有错误啊

追答

我行多试试

第2个回答  2012-03-14
你是哈师大的吧?追问

这都能猜到!!

追答

你是计科的把!