1 #include "stdio.h" 2 #include "malloc.h" 3 4 #define maxlen 100 5 #define infinity 65535 6 7 struct bnode 8 { 9 int data;//数据 10 bnode *lchild,*rchild; 11 bool flags;//使用标志 12 }; 13 14 bnode *tree[maxlen]; 15 16 void initialization(int A[],int N,bnode *tree[maxlen])//初始化 17 { 18 int i; 19 for(i=0;i<N;i++) 20 { 21 tree[i] = (bnode *)malloc(sizeof bnode);//分配存储区域 22 tree[i]->data = A[i];//结点的值 23 tree[i]->flags = true;//标识未使用 24 tree[i]->lchild = NULL;//左子树为空 25 tree[i]->rchild = NULL;//右子树为空 26 } 27 } 28 29 int merge(int n,bnode *tree[maxlen])//寻找当前根结点值最小的两个子树将其合并 30 { 31 int i,num1,num2,min1,min2; 32 min1 = infinity; 33 min2 = infinity; 34 for(i=0;i<n;i++)//寻找当前值最小的根节点 35 { 36 if((tree[i]->data<min1)&&tree[i]->flags) 37 { 38 min1 = tree[i]->data; 39 num1 = i; 40 } 41 } 42 tree[num1]->flags = false;//设置标识已使用过 43 44 for(i=0;i<n;i++)//寻找当前值最小的根节点 45 { 46 if((tree[i]->data<min2)&&tree[i]->flags) 47 { 48 min2 = tree[i]->data; 49 num2 = i; 50 } 51 } 52 tree[num2]->flags = false;//设置标识已使用过 53 //将两个子树合并 54 tree[n] =(bnode *)malloc(sizeof bnode);//分配存储区域 55 tree[n]->data = tree[num1]->data + tree[num2]->data; 56 tree[n]->flags = true; 57 tree[n]->lchild = tree[num1]; 58 tree[n]->rchild = tree[num2]; 59 n++; 60 return n; 61 } 62 63 int Huffmantree(int n,bnode *tree[maxlen])//构造哈夫曼树 64 { 65 int i,num; 66 bool flags = true;//标识 67 while(flags) 68 { 69 num = 0;//计数 70 for(i=0;i<n;i++)//统计未使用结点数 71 { 72 if(tree[i]->flags) 73 { 74 num++; 75 } 76 } 77 if(num>=2) 78 { 79 n = merge(n,tree);//合并当前根结点值最小的两棵子树 80 }else{ 81 flags = false;//哈夫曼树构造完成标识 82 } 83 } 84 return n; 85 } 86 87 88 void PrintTree(bnode *Tree,int nlayer) //按树状打印二叉树 89 { 90 if(Tree==NULL) 91 { 92 return ; 93 } 94 PrintTree( Tree->rchild,nlayer+1); //打印右子树 95 for(int i=0;i<nlayer;i++) 96 { 97 printf(" "); 98 } 99 printf("%d \n",Tree->data); 100 PrintTree(Tree->lchild,nlayer+1); //打印左子树 101 } 102 103 int main() 104 { 105 int x,nlayer=1; 106 int Array[maxlen];//存放节点的值 107 int count=0;//结点的个数 108 printf("[输入叶子结点,-1输入结束]:\n"); 109 printf("Data:"); 110 scanf("%d",&x); 111 while(x!=-1) 112 { 113 Array[count++] = x; 114 scanf("%d",&x); 115 } 116 117 initialization(Array,count,tree);//左右子树初始化 118 count = Huffmantree(count,tree);//构造哈夫曼树 119 120 printf("哈夫曼树树状输出:\n"); 121 122 PrintTree(tree[count-1],nlayer); 123 124 printf("\n"); 125 return 0; 126 }
时间: 2024-10-18 03:05:22