C语言 将二叉树转化为静态数组
//C语言,将动态二叉树转化为静态数组
#include
#include
//建立二叉树
struct treenode *createBiTree(struct treenode **p,int x);
//显示二叉树
void traverse(struct treenode *p);
//获取二叉树总的节点数并返回
int nodeNum(struct treenode *p);
//初始化数组的data数据,并使二叉树里面的arrayorder数据与数组下标一致
void initArray(struct treenode *p);
//将二叉树转化为数组
void transform(struct treenode *p);
struct treenode
{
int data;
struct treenode *left,*right;
int arrayorder;//转化为数组之后该节点在数组里的元素下标
};
struct treenode *createBiTree(struct treenode **p,int x)
{
if(*p==NULL)
{
*p=(struct treenode *)malloc(sizeof(struct treenode));
if (*p==NULL)
{
printf("out of memory,press any key to quit...\n");
exit(0);
}
(*p)->data=x;
(*p)->left=(*p)->right=NULL;
(*p)->arrayorder=0;
}
else if(xdata)
createBiTree(&(*p)->left,x);
else
createBiTree(&(*p)->right,x);
return (*p);
}
static int length=0;
int nodeNum(struct treenode *p)
{
if(p!=NULL)
{
length++;
nodeNum(p->left);
nodeNum(p->right);
}
return length;
}
void traverse(struct treenode *p)
{
if(p!=NULL)
{
printf("%d ",p->data);
traverse(p->left);
traverse(p->right);
}
}
struct treeArray
{
int data;
int lchild,rchild;
};
static struct treeArray *a=NULL;//转化之后的数组
static int num=0;
void initArray(struct treenode *p)
{
if(p!=NULL)
{
a[num].data=p->data;
p->arrayorder=num;
num++;
initArray(p->left);
initArray(p->right);
}
}
static int i=0;
void transform(struct treenode *p)
{
if(p!=NULL)
{
if(p->left!=NULL)
a[i].lchild=p->left->arrayorder;
if(p->right!=NULL)
a[i].rchild=p->right->arrayorder;
i++;
transform(p->left);
transform(p->right);
}
}
void main(void)
{
int x;
struct treenode *root=NULL;
//建立二叉树链表
printf("输入数据以\"ctrl+z\"结束:\n");
while(scanf("%d",&x)!=EOF)
createBiTree(&root,x);
printf("先序输出二叉树:");
traverse(root);//输出二叉链表
printf("\n");
//动态分配跟二叉树节点个数一样的静态数组
length=nodeNum(root);
a=(struct treeArray *)malloc(sizeof(struct treeArray)*length);
if (a==NULL)
{
printf("o