哈夫曼树

include <stdio.h>

include <stdlib.h>

include <string.h>

typedef struct stHuNode{
int data;
struct stHuNode* lchild, *rchild;
}HUNODE;

int findSmallData(HUNODE pArray[] ,int n,int p1, int* p2){
int index = 0;
int fir_small = 0xffff, sec_small = 0xffff;

if(pArray == NULL){
    return 1;
}

for(index = 0; index < n; index++){
    if(pArray[index] != NULL){
        if(pArray[index]->data < fir_small){
            sec_small = fir_small;
            fir_small = pArray[index]->data;

            *p2 = *p1;
            *p1 = index;                
        }
        else if(pArray[index]->data < sec_small){
            sec_small = pArray[index]->data;
            *p2 = index;
        }
    }       
}

return 0;

}

HUNODE* createHuTree(int* a, int n) {
int index = 0;

int fir_small = 0, sec_small = 0;
HUNODE *pArray[100];
HUNODE *pNewNode = NULL;
memset(pArray,0,sizeof(HUNODE)*n);
for(index = 0; index < n; index++){
    pNewNode = (HUNODE*)malloc(sizeof(HUNODE));
    memset(pNewNode,0,sizeof(HUNODE));
    pNewNode->data = a[index];
    pNewNode->lchild = NULL;
    pNewNode->rchild = NULL;
    pArray[index] = pNewNode;
}

for(index = 0; index < n-1; index++){
    findSmallData(pArray,n,&fir_small,&sec_small);
    pNewNode = (HUNODE*)malloc(sizeof(HUNODE));
    memset(pNewNode,0,sizeof(HUNODE)); 
    pNewNode->data = pArray[fir_small]->data + pArray[sec_small]->data;
    pNewNode->lchild = pArray[fir_small];
    pNewNode->rchild = pArray[sec_small];
    pArray[fir_small] = NULL;
    pArray[sec_small] = pNewNode;
}
return pNewNode;

}

void preOrderHuffMan(HUNODE* root){
if(root){
printf("%d ",root->data);
preOrderHuffMan(root->lchild);
preOrderHuffMan(root->rchild);
}
}

int main(){
int a[4] = {7,5,2,4};
HUNODE* root = NULL;
root = createHuTree(a,4);
preOrderHuffMan(root);
printf("\n");
return 0;
}

posted @ 2019-06-13 16:46  杨垚1  阅读(138)  评论(0编辑  收藏  举报