#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
struct treenode
{
int data
;
struct treenode
*left
,*right
;
int arrayorder
;
};
struct treeArray
{
int data
;
int lchild
,rchild
;
};
struct treenode
* createBiTree(struct treenode
**p
, int x
);
void traverse(struct treenode
*p
);
int nodeNum(struct treenode
* p
);
void initArray(struct treenode
* p
,struct treeArray
* pArr
);
void transform(struct treenode
* p
,struct treeArray
* pArr
);
int main()
{
int x
;
struct treenode
*root
= NULL;
printf("input data is continum?(ctrl+z): \n");
while(scanf("%d",&x
) != EOF)
{
createBiTree(&root
,x
);
}
traverse(root
);
printf("\n");
int nodeLen
= nodeNum(root
);
struct treeArray
* tArr
= (struct treeArray
*)malloc(sizeof(struct treeArray
) * nodeLen
);
if (tArr
== NULL)
{
printf("out of memory,press any key to quit...\n");
exit(0);
}
for (int i
= 0; i
< nodeLen
; ++i
)
{
tArr
[i
].data
= tArr
[i
].lchild
= tArr
[i
].rchild
= 0;
}
initArray(root
,tArr
);
transform(root
,tArr
);
printf("将二叉树转化为数组之后为:\n");
printf("下标 data lchild rchild\n");
for(int j
=0;j
<nodeLen
;j
++)
{
printf("%2d%8d%8d%8d\n",j
,tArr
[j
].data
,tArr
[j
].lchild
,tArr
[j
].rchild
);
}
free(tArr
);
tArr
= NULL;
return 0;
}
void transform(struct treenode
* p
,struct treeArray
* pArr
)
{
static int i
= 0;
if (p
!= NULL)
{
if(p
->left
!= NULL)
pArr
[i
].lchild
= p
->left
->arrayorder
;
if(p
->right
!= NULL)
pArr
[i
].rchild
= p
->right
->arrayorder
;
++i
;
transform(p
->left
,pArr
);
transform(p
->right
,pArr
);
}
}
void initArray(struct treenode
* p
,struct treeArray
* pArr
)
{
static int num
= 0;
if (p
!= NULL)
{
pArr
[num
].data
= p
->data
;
p
->arrayorder
= num
;
++num
;
initArray(p
->left
,pArr
);
initArray(p
->right
,pArr
);
}
}
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(x
< (*p
)->data
)
{
createBiTree(&(*p
)->left
,x
);
}
else
createBiTree(&(*p
)->right
,x
);
return *p
;
}
void traverse(struct treenode
*p
)
{
if (p
!= NULL)
{
printf("%d ",p
->data
);
traverse(p
->left
);
traverse(p
->right
);
}
}
int nodeNum(struct treenode
* p
)
{
static int num
= 0;
if (p
!= NULL)
{
++num
;
nodeNum(p
->left
);
nodeNum(p
->right
);
}
return num
;
}
转载请注明原文地址:https://tech.qufami.com/read-12978.html