生成哈夫曼树
给定权集{5,7,2,3,6,8,9}构造哈夫曼树
#include <stdio.h> #include <stdlib.h> #define ElemType int #define MAXSIZE 20 #define length 7 typedef struct HFNode{ ElemType weight; struct HFNode *lchild,*rchild; }HFNode,*HFTree; HFTree CreatHFTree(ElemType s[MAXSIZE]){ HFTree hftarr[MAXSIZE]; HFTree hft,root=NULL; for(int i=0;i<length;i++){ hft=(HFTree)malloc(sizeof(HFNode)); hft->weight=s[i]; hft->lchild=NULL; hft->rchild=NULL; hftarr[i]=hft; } for(int i=1;i<length;i++){ int w1=-1,w2;//w1为最小节点的下标,w2为次最下节点的下标 for(int j=0;j<length;j++){ if(hftarr[j]!=NULL&&w1==-1){ w1=j; continue; } if(hftarr[j]!=NULL){ w2=j; break; } } for(int j=w2;j<length;j++){ if(hftarr[j]!=NULL){ if(hftarr[j]->weight<hftarr[w1]->weight){ w2=w1; w1=j; } else if(hftarr[j]->weight<hftarr[w2]->weight){ w2=j; } } }//找出最小权重的两个节点 root=(HFTree)malloc(sizeof(HFNode)); root->weight=hftarr[w1]->weight+hftarr[w2]->weight; root->lchild=hftarr[w1]; root->rchild=hftarr[w2]; hftarr[w1]=root;//将生成的新树指针指向w1 hftarr[w2]=NULL; } return root; }//生成哈夫曼树 void visit(HFTree &T){ if(T!=NULL){ printf("%d ",T->weight); } } void PreOrder(HFTree &T){ if(T){ visit(T); PreOrder(T->lchild); PreOrder(T->rchild); } } int main(){ ElemType s[MAXSIZE]={5,7,2,3,6,8,9}; HFTree T; T=CreatHFTree(s); PreOrder(T); }