build_tree.asv
上传用户:xxhxxny
上传日期:2021-02-19
资源大小:87k
文件大小:2k
源码类别:

压缩解压

开发平台:

Matlab

  1. %==============================================
  2. % 根据字符的频率,生成Huffman树,保存在huffman_tree中
  3. % 最终生成的huffman树的节点(包括256内没有出现的字符)由
  4. % index_tree表示最终返回的根节点的位置
  5. %==============================================
  6. function [huffman_tree,index_tree] = build_tree(char_prob)  % Matlab函数可以返回多个值
  7. disp('buildng huffman tree...');
  8. huffman_tree.count=zeros(1,512);     % huffman_tree 结构包含三个成员:count--字符出现的频度
  9. huffman_tree.leftchild=zeros(1,512); % leftchild--左子节点的下标
  10. huffman_tree.rightchild=zeros(1,512);% rightchild--右子节点的下标
  11. huffman_tree.count(1:256)=char_prob; % 第1-256个初始化为ASCII码对应的字符出现的频度 
  12. huffman_tree.count(512)=inf;   %由于二叉树性质,所有树节点总和《=511,512的值为MAX,控制用
  13. index_tree=256+1;   %根节点最小为257
  14. while 1
  15.     min_1=512;
  16.     min_2=512;
  17.     for i=1:index_tree-1
  18.         if huffman_tree.count(i) ~=0   % 跳过没有出现的字符
  19.             if huffman_tree.count(i) < huffman_tree.count(min_1)   %寻找两个最小值,分别为min_1,min_2
  20.                 min_2=min_1;
  21.                 min_1=i;
  22.             elseif huffman_tree.count(i) < huffman_tree.count(min_2)
  23.                 min_2=i;
  24.             end
  25.         end        
  26.     end   % end of for
  27.     if min_2==512
  28.         break;
  29.     end
  30.     huffman_tree.count(index_tree)=huffman_tree.count(min_1)+huffman_tree.count(min_2);  % 将两个最小合并成新的节点
  31.     huffman_tree.count(min_1)=0;   % 
  32.     huffman_tree.count(min_2)=0;
  33.     huffman_tree.leftchild(index_tree)=min_1;
  34.     huffman_tree.rightchild(index_tree)=min_2;
  35.     
  36.     index_tree=index_tree+1;
  37. end  % end of while
  38. index_tree=index_tree-1;  %返回
  39. disp('completed!');