我自己用C語言編寫了一個,用層次隊列指標,建立了一個二叉樹。並在最後用了層次遍曆法對 二叉樹進行了遍曆。
程式源碼:
#define N 20
#define NULL 0
#define NT 0
#include "Stdio.h"
#include "Conio.h"
#include <math.h>
#define M 10
typedef int datatype;
typedef struct node /*二叉樹資料類型定義*/
{
datatype data;
struct node *lchild,*rchild;
}bitreend;
typedef struct ndlk
{
bitreend * nde;
struct ndlk * next;
}nodlk;
typedef struct /*有一個佇列儲存體當前訪問的*/
{
nodlk * nodlnk;
nodlk * tail;
}link;
link lnk;
void inilnk()
{
nodlk *p;
for(p=lnk.nodlnk;p;p=lnk.nodlnk)
{
lnk.nodlnk=lnk.nodlnk->next;
free(p);
}
lnk.tail=(nodlk *)NULL;
lnk.nodlnk=(nodlk *)NULL;
}
void addlnk(bitreend *nde)
{
nodlk *nl;
nl = (nodlk*)malloc(sizeof(nodlk));
nl->next=(nodlk *)NULL;
nl->nde=nde;
if(lnk.nodlnk==NULL)
{
lnk.nodlnk=nl;
lnk.tail=nl;
}
else
{
lnk.tail->next=nl;
lnk.tail=nl;
}
lnk.tail->next=(nodlk *)NULL;
}
bitreend * dellnk()
{
nodlk * nlk;
bitreend *nde;
if(lnk.nodlnk==NULL)
{
lnk.tail=(bitreend *)NULL;
return (bitreend *)NULL;
}
nlk = lnk.nodlnk;
nde = lnk.nodlnk->nde;
lnk.nodlnk=lnk.nodlnk->next;
free (nlk);
return nde;
}
bitreend* creat() /*建立二叉排序樹*/
{
bitreend *q,*t;
bitreend *bitnode;
int lc=2,i,counter,ct=0,m;
datatype x;
nodlk *nl;
printf("please input the node's information! %d is not value! -1 end all/n",NT);
printf("/n1 layer's information!/n");
scanf("%d",&x);
q=(bitreend *)malloc(sizeof(bitreend));
q->data = x;
q->lchild = (nodlk *)NULL;
q->rchild = (nodlk *)NULL;
t= q;
nl=(nodlk*)malloc(sizeof(nodlk));
nl->next=(nodlk *)NULL;
nl->nde=q;
lnk.nodlnk=nl;
lnk.tail=nl;
for(;lnk.tail!=NULL||lc<=M;lc++)
{
m=pow(2,lc-2-ct);
printf("/n%d layer's information!/n",lc);
for(counter=1;counter<=m;counter++)
{
bitnode=dellnk();
scanf("%d",&x);
if(x ==-1)
{
printf("input bitree end/n");
return t;
}
else if(x == NT)
{
bitnode->lchild = (nodlk *)NULL;
ct++;
}
else
{
q=(bitreend *)malloc(sizeof(bitreend));
q->data=x;
q->lchild = (nodlk *)NULL;
q->rchild = (nodlk *)NULL;
addlnk(q);
bitnode->lchild = q;
}
scanf("%d",&x);
if(x==-1)
{
return t;
}
else if(x == NT)
{
bitnode->rchild = (nodlk *)NULL;
ct++;
}
else
{
q=(bitreend *)malloc(sizeof(bitreend));
q->data=x;
q->lchild = (nodlk *)NULL;
q->rchild = (nodlk *)NULL;
addlnk(q);
bitnode->rchild = q;
}
}
}
return t;
}
void laytraverse(bitreend *bitree)
{
int flag;
int i=1,m=1,k=1,ct=0;
bitreend *nd;
nd=bitree;
printf(" %d",nd->data);
for(;nd!=NULL;nd=dellnk())
{ flag=0;
if(i==m)
{
printf("/n");
m+=pow(2,k-ct);
k++;
}
if(nd->lchild!=NULL)
{
printf(" %d",nd->lchild->data);
addlnk(nd->lchild);
}
else
flag=1;
if(nd->rchild!=NULL)
{ if(flag)
{
printf(" 0");
}
printf(" %d",nd->rchild->data);
addlnk(nd->rchild);
}
else
if(!flag)
{
printf(" 0");
}
else
{
ct++;
}
i+=2;
}
}
int main(void)
{
bitreend *bitree;
inilnk();
bitree=creat();
inilnk();
if(bitree==NULL)
{
printf("Create bitree error! /twill exit!/n");
exit(-1);
}
laytraverse(bitree);
getch();
return 0;
}