I'm trying to make binary code from a Huffman tree. I am stuck at tree traversal. To traverse tree and print code for every character frequency, I've written following code.
def printCode(node,prefix=""):
if node.left:
prefix = prefix+"0"
printCode(node.left,prefix)
elif node.right:
prefix = prefix+"1"
printCode(node.right,prefix)
elif node.internal ==False:
print(node.data,prefix)
printCode(node,prefix="") #need change
Here is the necessary explanation: If a node is not an internal node(node.internal=False) then it is a leaf, and at this point of traversal I'm printing the code with character frequencies. But i'm unable to go back to the previous internal node and continue with another branch of tree that has not been traversed yet. So this code is ended with only returning binary code for the first leaf of the tree.
The every node of tree is created with following code:
class Node:
def __init__(self,data,internal=False):
self.data = data #frequency of a char
self.internal = internal
self.left = None
self.right = None
node.internal
? – SPYBUG96