1#include"stdio.h"2#include"malloc.h"3 4 #defineMaxLen 1005 #defineInfinity 655356 7 structBNode8 {9 intData//DataTenBNode *lchild,*Rchild; One BOOLFlags//Use flags A }; - -BNode *Tree[maxlen]; the - voidInitialization (intA[],intN,bnode *tree[maxlen])//Initialize - { - inti; + for(i=0; i<n;i++) - { +Tree[i] = (BNode *)malloc(sizeofBNode);//Assigning storage Areas ATree[i]->data = A[i];//the value of the node atTree[i]->flags =true;//Identity not used -Tree[i]->lchild = NULL;//left dial hand tree is empty -Tree[i]->rchild = NULL;//Right sub-tree is empty - } - } - in intMergeintN,bnode *tree[maxlen])//find the two subtree with the lowest value of the current root node to merge it - { to inti,num1,num2,min1,min2; +Min1 =Infinity; -Min2 =Infinity; the for(i=0; i<n;i++)//find the root node with the lowest current value * { $ if((tree[i]->data<min1) &&tree[i]->flags)Panax Notoginseng { -Min1 = tree[i]->data; theNUM1 =i; + } A } theTree[num1]->flags =false;//set identity has been used + - for(i=0; i<n;i++)//find the root node with the lowest current value $ { $ if((tree[i]->data<min2) &&tree[i]->flags) - { -Min2 = tree[i]->data; thenum2 =i; - }Wuyi } theTree[num2]->flags =false;//set identity has been used - //merging two subtrees WuTree[n] = (BNode *)malloc(sizeofBNode);//Assigning storage Areas -Tree[n]->data = Tree[num1]->data + tree[num2]->data; AboutTree[n]->flags =true; $Tree[n]->lchild =TREE[NUM1]; -Tree[n]->rchild =tree[num2]; -n++; - returnN; A } + the intHuffmantree (intN,bnode *tree[maxlen])//Constructing Huffman Tree - { $ intI,num; the BOOLFlags =true;//Identification the while(Flags) the { thenum =0;//Count - for(i=0; i<n;i++)//Statistics unused node numbers in { the if(tree[i]->flags) the { Aboutnum++; the } the } the if(num>=2) + { -n = merge (N,tree);//merges two subtrees trees with the lowest value of the current root node the}Else{BayiFlags =false;//Huffman tree structure complete identification the } the } - returnN; - } the the the voidPrinttree (BNode *tree,intNlayer)//print binary tree by tree the { - if(tree==NULL) the { the return ; the } 94Printtree (tree->rchild,nlayer+1);//Print Right sub-tree the for(intI=0; i<nlayer;i++) the { theprintf" "); 98 } Aboutprintf"%d \ n",tree->data); -Printtree (tree->lchild,nlayer+1);//Print left sub-tree101 }102 103 intMain ()104 { the intX,nlayer=1;106 intArray[maxlen];//the value of the storage node107 intCount=0;//Number of nodes108printf"[Input Leaf junction,-1 input end]:\n");109printf"Data:"); thescanf"%d",&x);111 while(x!=-1) the {113array[count++] =x; thescanf"%d",&x); the } the 117Initialization (Array,count,tree);//left and right subtree initialization118Count = Huffmantree (Count,tree);//Constructing Huffman Tree119 -printf"Huffman tree-like output: \ n");121 122Printtree (tree[count-1],nlayer);123 124printf"\ n"); the return 0;126}
Huffman tree-like output