由一个数组创建一个完全二叉树
完全二叉树的定义:
(1)1---h层次, 1到 h-1这些层次必须是满元素
(2) h层如果没有满,那么叶子节点必须在左边。
一个数组 创建成一个完全二叉树
[解决办法]
3楼已经几乎给出答案了。这里在3楼的基础上给出完整代码。by the way, 实际上,这里的二叉树和堆非常类似。
- C/C++ code
#include <stdio.h>#include <stdlib.h>#include <memory.h>typedef struct Node{ int data; struct Node * LChild; struct Node * RChild;}BitNode,*BiTree;void CreateTree(BiTree *bt,int a[],int len,int index){ //从数组a中创建二叉树,len为数组a的长度-1。index初始值为0。 if(index>len) return; (*bt)=(BiTree)malloc(sizeof(BitNode)); (*bt)->data=a[index]; CreateTree(&((*bt)->LChild),a,len,2*index+1); CreateTree(&((*bt)->RChild),a,len,2*index+2);}int main(){ int arr[]={3,1,4,1,5,9,2,6,5,3,5,8,9,7,9}; BiTree root; CreateTree(&root,arr,sizeof(arr)/sizeof(int),0);}