标签:
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))
标签:
原文地址:http://www.cnblogs.com/jbjhome/p/4781963.html