温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

数据结构C++使用最小堆实现huffman树

发布时间:2020-04-06 14:26:48 来源:网络 阅读:498 作者:zheng_feng 栏目:编程语言

#pragma once

#include"Heap.h"//使用博客实现的堆

template<class T>

struct HuffmanNode//节点的结构信息

{

T _weight;

HuffmanNode<T>* _parent;

HuffmanNode<T>* _left;

HuffmanNode<T>* _right;

HuffmanNode(const T& weight)

:_weight(weight)

, _parent(NULL)

, _left(NULL)

, _right(NULL)

{}

};

template<class T>

class HuffmanTree//huffman树的实现

{

typedef HuffmanNode<T> Node;

public:

HuffmanTree()

:_root(NULL)

{}

~HuffmanTree()

{

_Destroy(_root);

_root = NULL;

}

Node* GetRootNode()

{

return _root;

}

void CreateHuffmanTree(const T* array, size_t size, const T& invalid)

{

assert(array && size > 0);

struct Compare

{

bool operator()(Node*& l, Node*& r)

{

return (l->_weight < r->_weight);

}

};

////Heap<Node*,Compare> minHeap(array, size);

Heap<Node*, Compare> minHeap;

for (size_t i = 0; i < size; ++i)

{

if (array[i] != invalid)

{

Node* node = new Node(array[i]);

minHeap.Push(node);

}


}

if (minHeap.Empty())

return;

Node* parent = minHeap.GetTop();

while (minHeap.Size() > 1)

{

Node* first = minHeap.GetTop();

minHeap.Pop();

Node* second = minHeap.GetTop();

minHeap.Pop();

parent = new Node(first->_weight+second->_weight);

parent->_left = first;

parent->_right = second;

minHeap.Push(parent);

}

_root = parent;

}

void LevelOrder()

{

queue<Node*> q;

if (_root == NULL)

return;

q.push(_root);

while (!q.empty())

{

Node* cur = q.front();

q.pop();

cout << cur->_weight << " ";

if (cur->_left)

q.push(cur->_left);

if (cur->_right)

q.push(cur->_right);

}

}

private:

void _Destroy(Node*& root)

{

if (root == NULL)

return;

_Destroy(root->_left);

_Destroy(root->_right);

delete root;

root = NULL;

}


protected:

Node* _root;

};

void TestTree()

{

int ar[] = { 2, 3, 6, 0, 4, 5, 1, 9, 7, 8 };

//int ar[] = { 1,1,1,1,2,2 };

HuffmanTree<int> tree;

tree.CreateHuffmanTree(ar, sizeof(ar) / sizeof(ar[0]), -1);

tree.LevelOrder();

}


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI