1.数组方法
#include <stdio.h>
#include<stdlib.h>
typedef struct node
{
int value;
struct node *pLeft;
struct node *pRight;
}BinaryTree;
BinaryTree *ArrTree(int arr[], int length)
{
BinaryTree *p = NULL;
p = (BinaryTree*)malloc(sizeof(BinaryTree)*length);
for (int i = 0;i < length;i++)
{
p[i].value = arr[i];
p[i].pLeft = NULL;
p[i].pRight = NULL;
}
for (int i = 0;i <= length / 2 - 1;i++)
{
if (2 * i + 1 <= length - 1)
p[i].pLeft = &p[2 * i + 1];
if (2 * i + 2 <= length - 1)
p[i].pRight = &p[2 * i + 2];
}
return p;
}
int main()
{
int a[] = { 1,2,3,4,5,6,7,8 };
int len = sizeof(a)/sizeof(a[0]);
BinaryTree *p = ArrTree(a, len);
for (int i = 0;i < len;++i)
{
printf("%d %d %d ", p[i].value,p[i].pLeft->value,p[i].pRight->value);
printf("\n");
}
return 0;
}