哈夫曼建树

输入是各个叶子节点的值,第一个是数值的个数,然后先序遍历这棵树

#include<iostream>
#include<queue>
using namespace std;
int n;
struct tree
{
    int data;
    tree * lson;
    tree * rson;
}*ans;

struct f
{
    tree * father;
    int num;

    bool operator<(const f x)const
    {
        return num>x.num;
    }
}exa;

priority_queue<f>q;

void init()
{
    cin>>n;
    int x;
    for(int i=1;i<=n;i++){
        cin>>x;
        tree * bitree = new tree;
        exa.father=bitree;
        exa.num=x;
        bitree->data=x;
        bitree->lson=NULL;
        bitree->rson=NULL;
        q.push(exa);
    }
}

void build()
{
    f tree1,tree2;
    while(q.size()>1){
        tree1=q.top();q.pop();
        tree2=q.top();q.pop();
        tree * newtree = new tree;
        exa.num=newtree->data=tree1.num+tree2.num;
        newtree->lson=tree1.father;
        newtree->rson=tree2.father;
        exa.father=ans=newtree;
        q.push(exa);
    }
}

void view(tree * s)
{
    if(s==NULL){return;}
    cout<<s->data<<endl;
    view(s->lson);
    view(s->rson);
}

int main()
{
    init();
    build();
    view(ans);
}

// 7 7 1 3 9 5 4 8
原文地址:https://www.cnblogs.com/ZGQblogs/p/9074011.html