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();
}
相關文章
- C++ priority_queueC++
- 【C++ STL】queue和priority_queueC++
- C++ STL 優先佇列 (priority_queue)C++佇列
- C++ priority_queue為例的比較函式C++函式
- STL(二十)priority_queue優先佇列容器佇列
- Solution - Atcoder ARC127E Priority Queue
- 資料結構&堆&heap&priority_queue&實現資料結構
- 例說資料結構&STL(七)——priority_queue資料結構
- C++ 遍歷queueC++
- uva 11997 priority_queue 應用舉例(超省時間!!!)
- C++【stack/queue】用法和例子C++
- C++ queue的注意事項C++
- C++初階(stack+queue)C++
- (C++) queue容器基礎知識C++
- c++中stack、queue、vector的用法C++
- What is the difference between Mysql InnoDB B+ tree index and hash index? Why does MongoDB use B-tree?MySqlIndexMongoDB
- 資料結構分析及其實現(Stack、Queue、Tree、LinkedList)資料結構
- Huffman演算法演算法
- 2013成都站D題||hdu4784 bfs+DP+priority_queue(思路從spfa得到啟示)
- C++ 學習筆記之——STL 庫 queueC++筆記
- 用優先佇列構造Huffman Tree及判斷是否為最優編碼的應用佇列
- Use any C++ Compiler with Visual StudioC++Compile
- 【資料結構與演算法】Huffman樹&&Huffman編碼(附完整原始碼)資料結構演算法原始碼
- LeetCode C++ 968. Binary Tree Cameras【Tree/DFS】困難LeetCodeC++
- 05-樹9 Huffman Codes
- Huffman編碼m檔案分析
- queue
- Huffman對檔案編碼和解碼
- jQuery queue()jQuery
- Queue Sort
- C++ Templates (2.2 使用Stack類别範本 Use of Class Template Stack )C++
- 【轉載】Kano Model — Ways to use it and NOT use it
- 1284 海港 普及組 NOIP2016 佇列基礎 簡單列舉 簡單模擬 優先佇列(priority_queue)佇列
- 【Java程式設計】使用Java模擬C/C++中的queue佇列Java程式設計C++佇列
- Queue+PriorityQueue
- UVA-LA 3135 2004年北京站C題 STL priority_queue自定義優先順序優先佇列的使用佇列
- the "in" use in mysqlMySql
- nginx useNginx