• 哈夫曼树的构造


    #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()
    {
    
    }
  • 相关阅读:
    PS封装ES流
    win7无法删除文件夹,提示“找不到该项目”
    声明
    ZR#1005
    ZR#1004
    ZR#1009
    ZR#1008
    ZR#1015
    ZR#1012
    ZR#985
  • 原文地址:https://www.cnblogs.com/ilovetheworld/p/10734845.html
Copyright © 2020-2023  润新知