1. 结构类型定义:

 

    public class HuffmanTree
    {
        
public int Weight { setget; }
        
public HuffmanTree Left { setget; }
        
public HuffmanTree Right { setget; }
    }

 

 

2. 构建树:

 

代码
        public static HuffmanTree CreateHuffmanTree(int[] data)
        {
            
if (data == null || data.Length < 1)
            {
                
throw new Exception("data");
            }

            IList
<HuffmanTree> list = new List<HuffmanTree>();
            
foreach (var d in data)
            {
                list.Add(
new HuffmanTree
                {
                    Weight 
= d,
                    Left 
= null,
                    Right 
= null
                });
            }

            HuffmanTree parent 
= new HuffmanTree();
            HuffmanTree left 
= new HuffmanTree();
            HuffmanTree right 
= new HuffmanTree();

            
while (list.Count > 1)
            {
                left 
= list.First(item => item.Weight == list.Min(i => i.Weight));
                list.Remove(left);
                right 
= list.First(item => item.Weight == list.Min(i => i.Weight));
                list.Remove(right);

                parent 
= new HuffmanTree
                {
                    Weight 
= left.Weight + right.Weight,
                    Left 
= left,
                    Right 
= right
                };
                list.Add(parent);
            }

            
return parent;
        }

 

 

3. 测试:

 

            int[] data = { 7,5,2,4};
            HuffmanTree tree 
= HuffmanCode.CreateHuffmanTree(data);

 

 download