哈夫曼树

/*
*用一个数组保存节点,前面n为叶子结点,因为哈夫曼树没有度为1的节点,所以总结点数为2*n-1,后面为组合的节点
*/
#include<iostream>
using namespace std;
typedef struct HTNODE{
	int weight;
	int parent;
	int lchild;
	int rchild;
}HTNOOD;

typedef struct LINKNODE{
    int weight;
    int index;
    LINKNODE * next;

}LINKNODE;


int getMinIndex(int n,HTNOOD * HT[],LINKNODE* head){//求最小值(这个函数是哈夫曼树的关键)
	LINKNODE *p=head;
	int count=0;
   for(int i=0;i<2*n-1;i++){
       if(HT[i]->parent==0&&HT[i]->weight!=0){//将已经排过序的节点排除掉和还未赋值的节点排除掉
	      LINKNODE* node=new LINKNODE;
	      node->weight=HT[i]->weight;
	      node->index=i;
	      p->next=node;
	      p=node;
	      ++count; 
	   }
   }
   LINKNODE *min=head->next;
    p=min->next;
   for(int i=0;i<count-1;i++){
       if((p->weight)<(min->weight)){
	      min=p;
	   }
	   p=p->next;
   } 
   return min->index;
}

void createHaffmanTree(int n,HTNOOD* HT[]){
	int length=2*n-1;
	int i=0;
	LINKNODE * head=new LINKNODE;
	while(i<length){//初始化数组 
	  HT[i]=new HTNOOD;
	  if(i<n){
	     cout<<"请输入权值"<<endl;
	     cin>>HT[i]->weight;
	  }else{
	    HT[i]->weight=0;
	  }
	 HT[i]->parent=HT[i]->lchild=HT[i]->rchild=0;
	 ++i;
	}
	for(int i=n;i<length;i++){
		int first=getMinIndex(n,HT,head);
		HT[i]->lchild=first;
		HT[first]->parent=i;
		int second=getMinIndex(n,HT,head);
		HT[i]->rchild=second;
		HT[second]->parent=i;
		HT[i]->weight=(HT[first]->weight)+(HT[second]->weight);
	}
	for(int i=0;i<length;i++){
	   cout<<HT[i]->weight<<endl;
	}
}

int main(){
	HTNOOD *HT[7];
	int n=4;//假设叶子结点为4个
	createHaffmanTree(n,HT);
}
posted @ 2018-10-31 14:00  Saruka的男朋友  阅读(288)  评论(0编辑  收藏  举报