Comp Sci Creating Huffman Tree with Coding Frequency

Click For Summary
To create a Huffman tree, the frequency of each character in a string is first determined, and a structure is defined to represent the tree nodes. A function is implemented to create individual nodes, but the challenge lies in determining the correct placement of nodes based on frequency. As nodes are added, the frequency values of parent nodes should be updated, which can be done in a single pass or through a recursive algorithm. An alternative approach involves creating a sorted array of frequencies and then constructing the tree using a linked list before balancing it with the Day-Stout-Warren algorithm. Understanding these methods is crucial for effectively implementing Huffman coding.
anonim
Messages
39
Reaction score
2
Homework Statement
Taking a string, creating the Huffman coding tree and encrypting each character
Relevant Equations
-
First, I get the string and I find the frequency of the every character. My struct is:
C:
typedef struct huffman_tree{
    char c;
    int freq; //unsigned?
    struct huffman_tree *left; // 0 (left)
    struct huffman_tree *right; // 1 (right)
}huffman_tree;

I write this to create Huffman tree:
Code:
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;
}
But I do not know how can I add the frequency the tree, how can I know the number should be right or left?
 
Physics news on Phys.org
Review the wiki article, it has an example of a Huffman tree with frequency values shown for each node that should make it obvious How to proceed.

https://en.wikipedia.org/wiki/Huffman_coding

As you add each node to the tree, then you can update the freq values of parent nodes.

Alternatively, you can create the tree in one pass and then walk through it to update the noncharacter nodes frequency values in the next pass. A recursive algorithm would work here.
 

Similar threads

  • · Replies 1 ·
Replies
1
Views
11K
  • · Replies 1 ·
Replies
1
Views
1K
  • · Replies 1 ·
Replies
1
Views
3K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 2 ·
Replies
2
Views
6K
  • · Replies 1 ·
Replies
1
Views
3K
  • · Replies 4 ·
Replies
4
Views
2K
Replies
1
Views
2K
  • · Replies 3 ·
Replies
3
Views
2K