[英]How to create a huffman tree in c (already have a sorted array)
我正在嘗試創建一個霍夫曼樹,我已經有一些用c語言編寫的頻率數組。 這是我的結構:
struct node
{
int value;
char letter; /* symbol */
struct node *left,*right; /* left and right subtrees */
};
typedef struct node Node;
在main()中,我有:
int main(){
Node *tree;
FILE *input, *output; //file input and output i am taking because i will take a input text file containing encoding of all 27 alphabets like a= 00001 b= 00010 etc.
buildHuffmanTree(&tree); // see it's function call there i already have done sorting of frequencies using qsort() BUT I DON'T KNOW WHAT TO DO AFTER.
return 0;
}
看這里 :
void buildHuffmanTree(Node **tree){
Node *temp;
Node *array[27];
int i, subTrees = 27;
int smallOne;
for (i=0;i<27;i++)
{
array[i] = malloc(sizeof(Node));
array[i]->value = englishLetterFrequencies[i]; //this englishLetterFrequencies[27] contains the the frequencies of all 27 alphabtets like ={81,27,1,12.....up to 27 index of this array}
array[i]->letter = i;
array[i]->left = NULL;
array[i]->right = NULL;
}
//here is the sorting part:
int i = 0; int d,p;
printf("the array frequency is \n");
for(d=0;d < 27;d++)
printf("%d ",array[d]->value);
// sorting of arrays
qsort(array,27,sizeof(*array),cmpfunc);
//////////////////////////
printf("\n the sorted array frequency is \n");
for(p=0;p < 27;p++)
printf("%d ",array[p]->value); //So now this array[p]->value contains all the sorted frequency.
//I DON'T KNOW WHAT TO DO NOW
return;
}
現在有了排序數組,我要記住的是..首先,我將采用前兩個節點(在我的遞增排序sortedarray []的第一個和第二個索引中),然后添加它們並再次排序,並使用它。 但是我不知道該怎么做。 我是一個初學者。 任何人都可以解釋如何執行它嗎?
M分配一個新節點。 取兩個最低頻率的節點並將它們分配給新節點的左側和右側,然后將它們的頻率之和作為新節點的值。 通過向下移動其他元素,從陣列中刪除兩個節點。 現在,通過將較大的元素上移一個,將新節點插入到數組中小於元素的值之后,大於元素大於值的前面。 數組現在減少了一個元素。
重復直到數組中有一個元素。 那是樹的根。
我最近正在學習HuffmanTree,例如:您有一個頻率數組,分別是7,9,2,6,3,排序后,它變成了2,3,6,7,9。我無法投放圖片為了我的卑鄙...您總是選擇數組的前兩個元素,所以2和3,
5
/ \
2 3
您可以將其添加到數組中並添加5並刪除2和3.so數組現在是5,6,7,9下一步是選擇5和6,因此您可以獲取:
11
/\
5 6
/ \
2 3
因此,刪除5和6,並將廣告11刪除到數組中,現在是7,9,11,選擇7和9,您可以得到:
16
/ \
7 9
刪除7和9,然后將16添加到數組中,現在是11,16,選擇11和16,您可以得到:
27
/ \
11 16
/\ /\
5 6 7 9
/\
2 3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.