在这里插入代码片
#include "stdio.h"
#include "malloc.h"
typedef struct node{
char data;
struct node *lchild,*rchild;
}Tree ,*btree;
//创建二叉树
void creat(btree *t){
char a;
scanf("%c",&a);
if(a==' '){
*t=NULL;
}else{
*t=(btree)malloc(sizeof(btree));//为二叉树申请存储空间
(*t)->data=a;
creat(&((*t)->lchild));
creat(&((*t)->rchild));
}
}
//先序遍历:根节点,左子树,右子树
void qian(btree t,int len){
if(t){
printf("%c位于第%d层\n",t->data,len);
qian(t->lchild,len+1);
qian(t->rchild,len+1);
}
}
//中序遍历:左子树,根节点,右子树
void zhong(btree t,int len){
if(t){
zhong(t->lchild,len+1);
printf("%c位于第%d层\n",t->data,len);
zhong(t->rchild,len+1);
}
}
//后序遍历:左子树,右子树,根节点
void hou(btree t,int len){
if(t){
hou(t->lchild,len+1);
hou(t->rchild,len+1);
printf("%c位于第%d层\n",t->data,len);
}
}
int main(){
btree t=NULL,t1;
int len=1,l,n,ln;
creat(&t);
printf("先序遍历:\n");
qian(t,len);
printf("\n");
printf("中序遍历:\n");
zhong(t,len);
printf("\n");
printf("后序遍历:\n");
hou(t,len);
printf("\n");
return 0;
}
二叉树遍历
最新推荐文章于 2025-11-23 23:25:20 发布
这篇博客介绍了如何创建和遍历二叉树。通过`creat`函数实现了输入字符流构建二叉树,然后使用先序、中序和后序遍历方法展示了节点在树中的层次。代码示例详细解释了遍历过程。
2187

被折叠的 条评论
为什么被折叠?



