1. 程式人生 > >二叉樹的順序儲存

二叉樹的順序儲存

#include <iostream>
using namespace std;
#define Max 16


void Create_Tree(int *Tree,int *node,int length)
{
int i;
int level;
Tree[1]=node[1];
for(i=2;i<length;i++)
{
level=1;
while(Tree[level]!=0)
{
if(node[i]<Tree[level])
level=2*level;
else
level=2*level+1;
}
Tree[level]=node[i];
}
}


int main()
{
int Tree[Max]={0};
int node[16]={0,18,6,65,5,69,61,14,7};// root=8
Create_Tree(Tree,node,16);
for(int i=1;i<Max;i++)
{
cout<<Tree[i]<<"\t";
if(i%5==0)
cout<<endl;
}
cout<<"節點的雙親資訊:"<<endl;
int j,k,l;
for(j=1;j<Max;j++)
if(Tree[j]==Tree[1])
cout<<"根節點"<<endl;
else
{
cout<<"節點"<<Tree[j]<<"的雙親為:"<<Tree[j/2]<<"\t";
   if(i%2==0)
cout<<endl;
}
for(k=1;k<Max;k++)
if(Tree[k]==0)
cout<<Tree[k]<<"沒有孩子節點"<<endl;
else
{
cout<<"節點"<<Tree[k]<<"的孩子節點為:"<<Tree[k*2]<<"  "<<Tree[k*2+1]<<"\t";
   if(i%2==0)
cout<<endl;
}
for(l=1;l<Max;l++)
if(Tree[2*l]==0&&Tree[2*l+1]==0)
cout<<"葉子"<<Tree[l]<<"\t";

return 0;
}