二叉树HuffmanTree

Posted teternity

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二叉树HuffmanTree相关的知识,希望对你有一定的参考价值。

构建一棵 HuffmanTree。

 

测试代码 main.cpp:

#include <iostream>
#include "HuffmanTree.h"

using std::cout;
using std::endl;

int main()
{
    auto il = { 1,2,3,4,5,6,7,8,9 };

    HuffmanTree<int> ht(il.begin(), il.end());
    ht.levelTraversal();
    cout << endl;

    return 0;
}

 

头文件 "HuffmanTree.h":

#pragma once


#include <queue>

template<typename _Ty>
class HuffmanTree
{
    struct Node
    {
        _Ty weight;
        Node* left = nullptr;
        Node* right = nullptr;
        Node(const _Ty& _w) :weight(_w) {}
    };

public:
    HuffmanTree() = default;

    template<typename _Iter>
    HuffmanTree(_Iter _it1, _Iter _it2)
    {
        if (_it1 == _it2) return;
        std::priority_queue<Node*, std::vector<Node*>, comp> pq;
        while (_it1 != _it2)
        {
            Node* temp = new Node(*_it1);
            pq.push(temp);
            temp = nullptr;
            ++_it1;
        }
        while (true)
        {
            if (pq.size() == 1)
            {
                root = pq.top();
                return;
            }
            Node* temp = new Node(pq.top()->weight);
            temp->left = pq.top();
            pq.pop();
            temp->weight += pq.top()->weight;
            temp->right = pq.top();
            pq.pop();
            pq.push(temp);
            temp = nullptr;
        }
    }

    ~HuffmanTree() { clear(root); }

    void levelTraversal()
    {
        if (root == nullptr) return;
        std::queue<Node*> nodePointers;
        nodePointers.push(root);
        Node* cur = nullptr;
        while (!nodePointers.empty())
        {
            cur = nodePointers.front();
            std::cout << cur->weight << " ";
            if (cur->left != nullptr) nodePointers.push(cur->left);
            if (cur->right != nullptr) nodePointers.push(cur->right);
            nodePointers.pop();
        }
    }

    struct comp
    {
        bool operator ()(const Node* _n1, const Node* _n2) { return _n1->weight > _n2->weight; }
    };

private:
    void clear(Node*& _root)
    {
        if (_root == nullptr) return;
        clear(_root->left);
        clear(_root->right);
        delete _root;
        _root = nullptr;
    }

private:
    Node* root = nullptr;
};

 

以上是关于二叉树HuffmanTree的主要内容,如果未能解决你的问题,请参考以下文章

构建Huffman哈夫曼最优二叉树,binarytree,Python

构建Huffman哈夫曼最优二叉树,binarytree,Python

哈夫曼树(最优二叉树)详解与构造

C++ 漫谈哈夫曼树

Huffman Tree

二叉树每个节点有一个权值,给定一棵二叉树,求权值和最大的值