build_tree.asv
上传用户:xxhxxny
上传日期:2021-02-19
资源大小:87k
文件大小:2k
- %==============================================
- % 根据字符的频率,生成Huffman树,保存在huffman_tree中
- % 最终生成的huffman树的节点(包括256内没有出现的字符)由
- % index_tree表示最终返回的根节点的位置
- %==============================================
- function [huffman_tree,index_tree] = build_tree(char_prob) % Matlab函数可以返回多个值
- disp('buildng huffman tree...');
- huffman_tree.count=zeros(1,512); % huffman_tree 结构包含三个成员:count--字符出现的频度
- huffman_tree.leftchild=zeros(1,512); % leftchild--左子节点的下标
- huffman_tree.rightchild=zeros(1,512);% rightchild--右子节点的下标
- huffman_tree.count(1:256)=char_prob; % 第1-256个初始化为ASCII码对应的字符出现的频度
- huffman_tree.count(512)=inf; %由于二叉树性质,所有树节点总和《=511,512的值为MAX,控制用
- index_tree=256+1; %根节点最小为257
- while 1
- min_1=512;
- min_2=512;
- for i=1:index_tree-1
- if huffman_tree.count(i) ~=0 % 跳过没有出现的字符
- if huffman_tree.count(i) < huffman_tree.count(min_1) %寻找两个最小值,分别为min_1,min_2
- min_2=min_1;
- min_1=i;
- elseif huffman_tree.count(i) < huffman_tree.count(min_2)
- min_2=i;
- end
- end
- end % end of for
- if min_2==512
- break;
- end
- huffman_tree.count(index_tree)=huffman_tree.count(min_1)+huffman_tree.count(min_2); % 将两个最小合并成新的节点
- huffman_tree.count(min_1)=0; %
- huffman_tree.count(min_2)=0;
- huffman_tree.leftchild(index_tree)=min_1;
- huffman_tree.rightchild(index_tree)=min_2;
-
- index_tree=index_tree+1;
- end % end of while
- index_tree=index_tree-1; %返回
- disp('completed!');