建立二叉树,输出其各种遍历结果

cy1183254286 cy1183254286 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
for(i=0;i<64;i++)
                            {
                                layer1[i]=layer2[i];
                            }

每次进行上面的操作原有的数据不会被覆盖吗?
或者下面这个程序应该按照什么样的流程走一遍

#include <stdio.h>
typedef int datatype;
#include<malloc.h>
//首先给出二叉树在二叉链表存储结构下的数据类型定义:
struct node
{
datatype v; //结点数据
struct node *Lchild; //左结点
struct node *Rchild; //右结点
};
//以下建立二叉树

//函数用于判断t是否为2的整数次方
int is2Pow(int t)
{
while(t>1)
{
if(t%2!=0)
{
return 0;
}
t=t/2;
}
return 1;
}
/*
按满二叉树的结点编号顺序输入数据(假设结点数据值为正整数)
使用0表示不存在的结点,-1表示输入结束
*/

struct node *create()
{
int i; //表示循环变量
datatype x; //进行录入数据
int n=0; //表示结点在整个数的编号
int n0faLayer=0; //表示某结点在某一层的编号
struct node *tree; //生成二叉树

struct node *layer1[64];
struct node *layer2[64];
tree=NULL;
printf("请输入数据 0表示不存在的结点, -1表示输入结束\n ");
while(1)
{
scanf("%d",&x); //进行录入数据
if(x<0) //当输入-1表示录入结束
{
break;
}
n++; //结点编号
if(x>0) //结点数据大于0,进行二叉树生成
{
if(tree==NULL) //表示树原来是空的,现在创建根结点
{
tree=(struct node*)malloc(sizeof(struct node));//进行分配空间
tree->v=x;
tree->Lchild=NULL;
tree->Rchild=NULL;
layer2[0]=tree;
}
else
{
//生成一个结点
struct node *t=(struct node *)malloc(sizeof(struct node));
t->v=x;
t->Lchild=NULL;
t->Rchild=NULL;
layer2[n0faLayer]=t; //把结点放入layer2
//把结点挂在父节点
if(n0faLayer%2==0)
{
layer1[n0faLayer/2]->Lchild=t; //左子树
}
else
{
layer1[n0faLayer/2]->Rchild=t; //右子树
}
n0faLayer++;
}
}
else if(x==0) //等于0的情况
{
struct node*t=NULL;
layer2[n0faLayer]=t;
n0faLayer++;
}
//如果 n+1为2的整数次方,表示一层结束
if(is2Pow(n+1))
{
for(i=0;i<64;i++)
{
layer1[i]=layer2[i];
}
n0faLayer=0;
}
}
return tree;
}
//先序遍历
void first(struct node *tree)
{
if(tree==NULL)
{
//是一颗空树;
}
else
{
//先遍历根-先输出根的值
printf("%d\t",tree->v);
//其次访问左子树
first(tree->Lchild);
//最后访问有字数
first(tree->Rchild);
}
}
//中序遍历
void mid(struct node *tree)
{
if(tree==NULL)
{
//是一颗空树;
}
else
{
//中根遍历先输出左子树
mid(tree->Lchild);
//其次访问左子树
printf("%d\t",tree->v);
mid(tree->Rchild);
}
}
//后序遍历
void last(struct node *tree)
{
if(tree==NULL)
{
//是一颗空树;
}
else
{
last(tree->Lchild);
last(tree->Rchild);
printf("%d\t",tree->v);
}
}

int main()
{
struct node *tree=create();
printf("\n");
printf("先序遍历的结果为:\n");
first(tree);
printf("\n");
printf("中序遍历的结果为:\n");
mid(tree);
printf("\n");
printf("后序遍历的结果为:\n");
last(tree);
printf("\n");
return 0;
}
...全文

相关推荐

评论 5
收藏 已收藏
分享
返回顶部
cy1183254286
C语言 70,039 成员 243,237 内容