12.07.2015 Views

A Practical Introduction to Data Structures and Algorithm Analysis

A Practical Introduction to Data Structures and Algorithm Analysis

A Practical Introduction to Data Structures and Algorithm Analysis

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Sec. 5.6 Huffman Coding Trees 195// Build a Huffman tree from list huffliststatic HuffTree buildTree(List hufflist) {HuffTree tmp1, tmp2, tmp3;LettFreq tmpnode;for(hufflist.moveToPos(1); hufflist.length() > 1;hufflist.moveToPos(1)) {// While at least two items lefthufflist.moveToStart();tmp1 = hufflist.remove();tmp2 = hufflist.remove();tmpnode = new LettFreq(tmp1.weight() + tmp2.weight());tmp3 = new HuffTree(tmpnode, tmp1, tmp2);}// return <strong>to</strong> the list in sorted orderfor (hufflist.moveToStart();hufflist.currPos() < hufflist.length();hufflist.next())if (tmp3.weight() = hufflist.length())hufflist.append(tmp3); // This is heaviest value}hufflist.moveToStart(); // This is only tree on listreturn hufflist.remove(); // Return the treeFigure 5.29 Implementation for the Huffman tree construction function.buildHuff takes as input fl, the min-heap of partial Huffman trees, whichinitially are single leaf nodes as shown in Step 1 of Figure 5.25. The body offunction buildTree consists mainly of a for loop. On each iteration of thefor loop, the first two partial trees are taken off the heap <strong>and</strong> placed in variablestemp1 <strong>and</strong> temp2. A tree is created (temp3) such that the left <strong>and</strong> right subtreesare temp1 <strong>and</strong> temp2, respectively. Finally, temp3 is returned <strong>to</strong> fl.VUl 1l 2XFigure 5.30 An impossible Huffman tree, showing the situation where the twonodes with least weight, l 1 <strong>and</strong> l 2 , are not the deepest nodes in the tree. Trianglesrepresent subtrees.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!