1 #!/usr/bin/python 2 #coding=utf-8 3 #哈夫曼树创建 4 5 class Node(): 6 def __init__(self,value,left=None,right=None): 7 self.value=value 8 self.left=left 9 self.right=right 10 class Halfman(): 11 def init(self,k): 12 k.sort() 13 # key=Node(k[0]) 14 self.root=Node(k[0]) 15 if len(k)==len(set(k)): #无重复项判定 16 for i in range(1,len(k)): 17 node=Node(k[i]) 18 if i==1: 19 max=k[i]*(len(k)-i)+self.root.value*(len(k)-1) 20 else: 21 max=k[i]*(len(k)-i)+self.root.value 22 root=Node(max,self.root,node) 23 self.root=root 24 return self.root 25 def pre(self,root): 26 if root==None:return 27 print root.value 28 self.pre(root.left) 29 self.pre(root.right) 30 31 k=[2,8,5,6,4,7,9,1,3] 32 tree=Halfman() 33 a=tree.init([2,8,5,6,4,7,9,1,3]) 34 35 tree.pre(a) 36 37 print '*'*40 38 39 print a.value 40 print a.left.value 41 print a.right.value