class binaryTreeNode():
def __init__(self,data=None):
self.data = data
self.left = None
self.right = None
def returnData(self):
return self.data
def printBinaryTree(self,s = '---'):
if self.data:
print(s+self.data)
s = ' ' + s
if self.left:
self.left.printBinaryTree(s)
if self.right:
self.right.printBinaryTree(s)
def huffmanCode(dictionary):
current_nodes = sorted([[binaryTreeNode(item[0]),item[1]] for item
in dictionary.items()],key=lambda x: x[1])
while len(current_nodes) > 1:
newNode = binaryTreeNode(current_nodes[0][0].data+current_nodes[1][0].data)
newNode.left = current_nodes[1][0]
newNode.right = current_nodes[0][0]
newSum = current_nodes[0][1] + current_nodes[1][1]
current_nodes = sorted([[newNode,newSum]] + current_nodes[2:],key=lambda x: x[1])
return current_nodes[0][0]
def convertToBinary(tree,c,string=''):
if tree.left == None and tree.right == None:
return c+': '+string
else:
if c in tree.left.data:
return convertToBinary(tree.left,c,string+'0')
else:
return convertToBinary(tree.right,c,string+'1')