anonim
anonim

Reputation: 57

Huffman Tree Coding

How can I insert data to huffman tree in c?

huffman_tree *huffman_node_create(char data, unsigned int frequency)
{
    huffman_tree *node = malloc(sizeof(huffman_tree));

        node->data = data;
        node->frequency = frequency;
        node->left = NULL;
        node->right = NULL;

    return node;
}

I write this to create Huffman tree. But I do not know how can I add the frequency the tree, how can I know the number should be right or left?

and:

typedef struct huffman_tree{
    char c;
    int freq; //unsigned?
    struct huffman_tree *left; // 0 (left)
    struct huffman_tree *right; // 1 (right) 
}huffman_tree;

Upvotes: 0

Views: 1668

Answers (2)

It doesn't matter if they're right or left, actually.

The way to construct a Huffman tree is to keep selecting the two lowest frequencies and combining them into a tree node so that one becomes the left child, the other the right, and the combined frequency is the sum of the two frequencies. This combined node is put in the table, replacing its two children. The tree gets built gradually as previously combined nodes get paired with others. This process continues until all frequencies have been combined into a single tree.

Upvotes: 2

zimmij73
zimmij73

Reputation: 1

Maybe take a look at this? https://www.geeksforgeeks.org/huffman-coding-greedy-algo-3/ In general Numbers go to the left if they are smaller and to the right if they are larger than the previous node.

Upvotes: -1

Related Questions