实现哈夫曼树 Python和C++

下面是一个简单的Python实现哈夫曼树的程序:

class Node:
    def __init__(self, freq, symbol):
        self.freq = freq
        self.symbol = symbol
        self.left = None
        self.right = None

def huffman_tree(data):
    # 统计字符频率
    freq = {}
    for symbol in data:
        freq[symbol] = freq.get(symbol, 0) + 1

    # 创建叶子节点
    nodes = []
    for symbol, freq in freq.items():
        nodes.append(Node(freq, symbol))

    # 构建哈夫曼树
    while len(nodes) > 1:
        nodes = sorted(nodes, key=lambda x: x.freq)

        left = nodes[0]
        right = nodes[1]

        parent = Node(left.freq + right.freq, None)
        parent.left = left
        parent.right = right

        nodes = nodes[2:]
        nodes.append(parent)

    return nodes[0]

def huffman_encoding(data, node, prefix="", code={}):
    if node is None:
        return

    if node.symbol is not None:
        code[node.symbol] = prefix

    huffman_encoding(data, node.left, prefix + "0", code)
    huffman_encoding(data, node.right, prefix + "1", code)

    return code

def huffman_decoding(data, node):
    result = ""
    current = node

    for bit in data:
        if bit == "0":
            current = current.left
        else:
            current = current.right

        if current is not None and current.symbol is not None:
            result += current.symbol
            current = node

    return result


data = "Hello, world!"
tree = huffman_tree(data)
code = huffman_encoding(data, tree)
encoded_data = "".join([code[symbol] for symbol in data])
decoded_data = huffman_decoding(encoded_data, tree)

print("原始数据:", data)
print("哈夫曼编码:", encoded_data)
print("解码后数据:", decoded_data)

这个程序首先通过统计字符频率来构建叶子节点列表,然后循环构建哈夫曼树,直到只剩下一个根节点。接下来,通过遍历哈夫曼树来生成每个字符的编码。最后,使用生成的编码来对原始数据进行编码和解码。

以下是一个使用C++实现哈夫曼树的简单示例代码:

#include 
#include 
using namespace std;

// 哈夫曼树节点
struct Node {
    int frequency;
    char character;
    Node* left;
    Node* right;
    
    Node(int f, char c)
    {
        frequency = f;
        character = c;
        left = right = nullptr;
    }
};

// 用于比较节点的优先队列
struct Compare {
    bool operator()(Node* a, Node* b)
    {
        return a->frequency > b->frequency;
    }
};

// 构建哈夫曼树
Node* buildHuffmanTree(priority_queue, Compare>& pq)
{
    while (pq.size() > 1) {
        Node* leftChild = pq.top();
        pq.pop();
        
        Node* rightChild = pq.top();
        pq.pop();
        
        // 创建新节点,频率为左右子节点频率之和
        Node* newNode = new Node(leftChild->frequency + rightChild->frequency, '#');
        newNode->left = leftChild;
        newNode->right = rightChild;
        
        pq.push(newNode);
    }
    
    return pq.top();
}

// 打印哈夫曼编码
void printHuffmanCodes(Node* root, string code)
{
    if (root == nullptr) {
        return;
    }
    
    // 叶子节点
    if (root->left == nullptr && root->right == nullptr) {
        cout << root->character << ": " << code << endl;
    }
    
    printHuffmanCodes(root->left, code + "0");
    printHuffmanCodes(root->right, code + "1");
}

int main()
{
    // 输入字符及其频率
    int n;
    cout << "Enter the number of characters: ";
    cin >> n;
    
    priority_queue, Compare> pq;
    for (int i = 0; i < n; i++) {
        char c;
        int f;
        cout << "Enter character and its frequency: ";
        cin >> c >> f;
        
        Node* newNode = new Node(f, c);
        pq.push(newNode);
    }
    
    Node* root = buildHuffmanTree(pq);
    
    cout << "Huffman Codes:" << endl;
    printHuffmanCodes(root, "");
    
    return 0;
}

这段代码首先会要求输入字符的数量和每个字符的频率,然后会构建哈夫曼树,并打印出每个字符对应的哈夫曼编码。需要注意的是,这里使用了优先队列来存储节点,并通过自定义比较函数对节点进行排序。

你可能感兴趣的:(开发语言,c++,算法,python)