P. 1


|Views: 53|Likes:
Published by kantti

More info:

Published by: kantti on May 15, 2008
Copyright:Attribution Non-commercial


Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See more
See less





In a sense, encoding a message is harder than decoding, because for a given

letter we might have to search the tree to find the leaf node that contains the

letter, and then figure out the path from the root to that node.

This process is much more efficient if we traverse the tree once, compute all the

codes, and build a Map from letters to codes.

By now we have seen plenty of tree traversals, but this one is unusual because as

we move around the tree, we want to keep track of the path we are on. At first,

that might seem hard, but there is a natural way to perform this computation

recursively. Here is the key observation: if the path from the root to a given

node is represented by a string of dots and dashes called path, then the path to

the left child of the node is path + ’-’ and the path to the right child is path

+ ’.’.

Exercise 20.18

a. Write a class definition for CodeTab, which extends HashMap.

b. In the CodeTab definition, write a recursive method called getCodes that tra-

verses a HuffTree in any order. When it reaches a leaf node, it should print the

letter in the node and the code that represents the path from the root to the



Huffman code

c. Once getCodes is working, modify it so that when it reaches a leaf node, it

makes an entry in the HashMap, with the letter as the key and the code as the


d. Write a constructor for CodeTab that takes a HuffTree as a parameter and that

invokes getCodes to build the code table.

e. In the Huffman class, write a method called encode that traverses a string, looks

up each character in the code table, and returns the encoding of the string. Test

this method by passing the result to decode and see if you get the original string


You're Reading a Free Preview

/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->