#include<iostream> #include<string> using namespace std; struct ElemType { char date; int weight; }; struct HTNode { char data; int weight; int parent,lchild,rchild; string code; }; HTNode *createTree(ElemType *w,int n)//哈夫曼树构造 { HTNode *ht=new HTNode[2*n]; int i,p1,p2; for(i=1;i<n;i++)//叶子节点初始化 { ht[i].data=w[i].date; ht[i].weight=w[i].weight; ht[i].parent=ht[i].lchild=ht[i].rchild=0; } for(i=n+1;i<2*n;i++)//非叶子节点初始化 { ht[i].weight=ht[i].parent=ht[i].lchild=ht[i].rchild=0; } for(i=n+1;i<2*n;i++) { Select(ht,1,i,p1,p2);//选中权重最小的两个 ht[p1].parent=ht[p2].parent=i; ht[i].lchild=p1; ht[i].rchild=p2; ht[i].weight=ht[p1].weight+ht[p2].weight; } return ht; } void CreateCode(HTNode *ht,int n) { ht[2*n-1].code=""; for(int i=2*n-1;i>n;i--) { int left=ht[i].lchild; int right=ht[i].rchild; ht[left].code=ht[i].code+"0"; ht[right].code=ht[i].code+"1"; } } int main() { }
原文地址:https://www.cnblogs.com/ilovetheworld/p/10734845.html
时间: 2024-09-30 14:41:53