Huffman Tree (use priority queue) in C++

Use the priority queue to implement Huffman Tree, written in C++ and use STL.

#include <iostream>
#include <stdlib.h>
#include <queue>
#include <vector>
using namespace std;

struct Node
{
    int val;
    struct Node * left;
    struct Node * right;
};

typedef struct Node * p_Node;

struct cmp
{
    bool operator () (p_Node const &p1, p_Node const &p2)
    {
        return p1->val > p2->val;
    }
};

p_Node createNode(int val, p_Node left, p_Node right)
{
    p_Node node = (p_Node)malloc(sizeof(struct Node));
    node->val = val;
    node->left = left;
    node->right = right;

    return node;
}

p_Node buildTree(int * vec, int n)
{
    priority_queue<p_Node, vector<p_Node>, cmp> forest;

    for(int i = 0; i < n; i++)
    {
        p_Node node = createNode(vec[i], NULL, NULL);
        forest.push(node);
    }

    while(forest.size() > 1)
    {
        p_Node node1 =  forest.top();
        forest.pop();
        p_Node node2 =  forest.top();
        forest.pop();
        cout<<node1->val<<"  "<<node2->val<<endl;
        p_Node new_node = createNode(node1->val + node2->val, node1, node2);
        forest.push(new_node);
    }
    return forest.top();
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 10,029评论 0 23
  • “哼!狗屁的云中剑仙!提前步好机关,覆上白粉,行动时炸起机关,扬起白粉,隐于其中杀人而已。哪里是剑仙,分明是手段下...
    银钩铁画张地瓜阅读 284评论 0 3
  • 今天又在想大学生该做些什么,吉他还没到,手机站领可了我的闲暇时光,时间和生命我都浪费了, 我想念家乡的朋友,和小时...
    水影冰茶阅读 246评论 0 0