11.07.2015 Views

Data Structures and Algorithm Analysis - Computer Science at ...

Data Structures and Algorithm Analysis - Computer Science at ...

Data Structures and Algorithm Analysis - Computer Science at ...

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

184 Chap. 5 Binary Trees/** Build a Huffman tree from list hufflist */st<strong>at</strong>ic HuffTree buildTree() {HuffTree tmp1, tmp2, tmp3 = null;}while (Hheap.heapsize() > 1) { // While two items lefttmp1 = Hheap.removemin();tmp2 = Hheap.removemin();tmp3 = new HuffTree(tmp1.root(), tmp2.root(),tmp1.weight() + tmp2.weight());Hheap.insert(tmp3); // Return new tree to heap}return tmp3;// Return the treeFigure 5.29 Implement<strong>at</strong>ion 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 iter<strong>at</strong>ion 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 cre<strong>at</strong>ed (temp3) such th<strong>at</strong> the left <strong>and</strong> right subtreesare temp1 <strong>and</strong> temp2, respectively. Finally, temp3 is returned to fl.VUl1l2XFigure 5.30 An impossible Huffman tree, showing the situ<strong>at</strong>ion where the twonodes with least weight, l 1 <strong>and</strong> l 2 , are not the deepest nodes in the tree. Trianglesrepresent subtrees.Proof: The proof is by induction on n, the number of letters.• Base Case: For n = 2, the Huffman tree must have the minimum externalp<strong>at</strong>h weight because there are only two possible trees, each with identicalweighted p<strong>at</strong>h lengths for the two leaves.• Induction Hypothesis: Assume th<strong>at</strong> any tree cre<strong>at</strong>ed by buildHuff th<strong>at</strong>contains n − 1 leaves has minimum external p<strong>at</strong>h length.• Induction Step: Given a Huffman tree T built by buildHuff with nleaves, n ≥ 2, suppose th<strong>at</strong> w 1 ≤ w 2 ≤ · · · ≤ w n where w 1 to w n arethe weights of the letters. Call V the parent of the letters with frequencies w 1<strong>and</strong> w 2 . From the lemma, we know th<strong>at</strong> the leaf nodes containing the letterswith frequencies w 1 <strong>and</strong> w 2 are as deep as any nodes in T. If any other leaf

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

Saved successfully!

Ooh no, something went wrong!