#include
#include
typedef struct bitnode{
char date;
struct bitnode *lchild,*rchild;
}bitnode, *bitree;
//建立二叉树
void createbitree(bitree &t)
{char ch;
scanf("%c",&ch);
if(ch==' ') t=NULL;
else {t=(bitnode*)malloc(sizeof(bitnode));
t->date=ch;
createbitree(t->lchild);
createbitree(t->rchild);
}
}
//二叉树的先根遍历
void preorder(bitree t)
{if (t!=NULL){
preorder(t->lchild);
preorder(t->rchild);
printf("%c",t->date);
}
}
//先根遍历的非递归先根遍历
void preorder2(bitree t)
{bitree s[100],p=t;
int top=0;
if(p){s[top++]=p;
while(top!=0)
{--top;
p=s[top];
printf("%c",p->date);
if(p->rchild)
s[top++]=p->rchild;
if(p->lchild)
s[top++]=p->lchild;
}
}
}
void main()
{bitree t;
char a;
createbitree(t); getchar();
printf("想用递归遍历?(y/n)");
scanf("%c",&a);
printf("%c\n",a);
if(a=='y') {preorder(t); printf("此为递归。");}
else
{preorder2(t);
printf("此为非递归遍历。");}
}
--------------------next---------------------
阅读(1558) | 评论(0) | 转发(0) |