建立完全二叉树

完全二叉树

对于完全二叉树,按顺序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]开始,那么数组与树的编号就一致了。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值