完全二叉树
对于完全二叉树,按顺序1~n编号,若父节点为i;则左孩子为2i,右孩子为2i+1;若树深度为k,则前k-1为满二叉树;因此判定当2i<=n时,建立左子树,当2i+1<=n时,建立又子树
#include<iostream>
#include<stdio.h>
#include<malloc.h>
#include<queue>
using namespace std;
typedef struct node
{
int data;
struct node *leftchild;
struct node *rightchild;
}Tree;
Tree* create(int a[],int n)
{
Tree *root=(Tree*)malloc(sizeof(Tree)*(n+1));
int i;
for(i=1;i<=n;i++)
{
root[i].data=a[i];//数组a只起到一个赋值的作用
root[i].leftchild=NULL;
root[i].rightchild=NULL;
}
for(i=1;i<=n/2;i++)// 判定条件
{
if(2*i<=n)
root[i].leftchild=&root[2*i];//把第2*i个结点的地址赋给左孩子
if(2*i+1<=n)
root[i].rightchild=&root[2*i+1];
}
return &root[1];//返回根地址
}
void preorder(node* &root)//层序遍历(stl模板建立指针队列,每一个指针入队时,当左右孩子存在,压其入队)
{
queue<node*>q;
q.push(root);
while(!q.empty())
{
printf("%4d",q.front()->data);
if(q.front()->leftchild)q.push(q.front()->leftchild);
if(q.front()->rightchild)q.push(q.front()->rightchild);
q.pop();//pop掉队首指针
}
}
int main()
{
int n,a[110];
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
}
Tree* root=NULL;
root=create(a,n);
preorder(root);
return 0;
}
因为数组是从0开始计数,而树从1开始,为了便于理解与方便,我将数组首位从[1]开始,那么数组与树的编号就一致了。