建立HuffMan树,利用的数组指针
#include "stdafx.h"
#include "stdio.h"
#define MAX 4 //叶节点的数目
struct node
{
int value;
node* left;
node *right;
node()
{
left=right=NULL;
}
};
int main(int argc, char* argv[])
{
node * shuzu[MAX];
for(int i=0;i<MAX;i++)
shuzu[i]=new node;
shuzu[0]->value=3; // 叶节点赋值
shuzu[1]->value=4;
shuzu[2]->value=3;
shuzu[3]->value=2;
int remainnum=4;
while(remainnum>1)
{
for(int i=0;i<remainnum;i++) //排序
{
for(int j=i+1;j<remainnum;j++)
{
if(shuzu[i]->value<shuzu[j]->value)
{
node *temp;
temp=shuzu[i];
shuzu[i]=shuzu[j];
shuzu[j]=temp;
}
}
}
node * point=new node; //最小两个节点 合并
point->value=shuzu[remainnum-1]->value+shuzu[remainnum-2]->value;
point->left=shuzu[remainnum-1];
point->right=shuzu[remainnum-2];
shuzu[remainnum-2]= point;
remainnum--;
}
node *tree=shuzu[0]; //剩下最后一个就是根节点
return 0;
}