码迷,mamicode.com
首页 > 编程语言 > 详细

Python 简明构建哈夫曼树

时间:2015-09-04 18:29:56      阅读:873      评论:0      收藏:0      [点我收藏+]

标签:

 1 import random
 2 #定义节点
 3 class Node:
 4     def __init__(self,weight=0,left=None,right=None):
 5         self.weight=weight
 6         self.left=left
 7         self.right=right
 8 #按权值排序
 9 def sort(list):
10     return sorted(list,key=lambda node:node.weight)
11 #构建哈夫曼树
12 def Huffman(list):
13     while len(list)!=1:
14         a,b=list[0],list[1]
15         new=Node()
16         new.weight=a.weight+b.weight
17         new.left,new.right=a,b
18         list.remove(a)
19         list.remove(b)
20         list.append(new)
21         list=sort(list)
22     return list
23 #中序遍历
24 def traval(First):
25         if First==None : return
26         traval(First.left)
27         print First.weight
28         traval(First.right)
29 #获得树的长度
30 def get_height(node):
31     if node.left==None and node.right==None: return 1
32     return  get_height(node.left)+get_height(node.right)
33 
34 # list=[]
35 #
36 # for i in range(1,11):
37 #     list.append(Node(i))
38 #
39 # list=sort(list)
40 #
41 #
42 # head=Huffman(list)[0]
43 # print(get_height(head))

 

Python 简明构建哈夫曼树

标签:

原文地址:http://www.cnblogs.com/jbjhome/p/4781963.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!