1.结点添加的简单方式
#include <stdio.h>
#include<stdlib.h>
typedef struct node
{
int value;
struct node *pLeft;
struct node *pRight;
}BinaryTree;
BinaryTree *CreateTree()
{
BinaryTree *pRoot = NULL;
pRoot = (BinaryTree*)malloc(sizeof(BinaryTree));
pRoot->value =1;
pRoot->pLeft =NULL;
pRoot->pRight=NULL;
//根的左
pRoot->pLeft= (BinaryTree*)malloc(sizeof(BinaryTree));
pRoot->pLeft->value = 2;
pRoot->pLeft->pLeft=NULL;
pRoot->pLeft->pRight =NULL;
//左的左
pRoot->pLeft->pLeft =(BinaryTree*)malloc(sizeof(BinaryTree));
pRoot->pLeft->pLeft->value =4;
pRoot->pLeft->pLeft->pLeft = NULL;
pRoot->pLeft->pLeft->pRight =NULL;
//左的右
pRoot->pLeft->pRight =(BinaryTree*)malloc(sizeof(BinaryTree));
pRoot->pLeft->pRight->value =5;
pRoot->pLeft->pRight->pLeft =NULL;
pRoot->pLeft->pRight->pRight =NULL;
//根的右
pRoot->pRight= (BinaryTree*)malloc(sizeof(BinaryTree));
pRoot->pRight->value =3;
pRoot->pRight->pLeft=NULL;
pRoot->pRight->pRight =NULL;
//右的左
pRoot->pRight->pLeft =(BinaryTree*)malloc(sizeof(BinaryTree));
pRoot->pRight->pLeft->value =6;
pRoot->pRight->pLeft->pLeft= NULL;
pRoot->pRight->pLeft->pRight =NULL;
return pRoot;
}
2.通过传入数组的方式
利用完全二叉树的性质,二叉树的结点值等于传入数组的值,根结点编号为0,编号为i的结点,当2*i+1<=n-1;该结点存在左孩子,当2*i+2<=n-1;该结点存在右孩子
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;
}