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.

192 Chap. 5 Binary Trees3060 1120 186E 0790 110107137U42D42L06532 33C0 19 240 1 M2Z17KFigure 5.26 A Huffman tree for the letters of Figure 5.24.<strong>and</strong> IntlNode. This implementation reflects the fact that leaf <strong>and</strong> internal nodescontain distinctly different information.Figure 5.28 shows the implementation for the Huffman tree. Nodes of the trees<strong>to</strong>re key-value pairs (see Figure 4.30), where the key is the weight <strong>and</strong> the value isthe character. Figure 5.29 shows the Java code for the tree-building process.Huffman tree building is an example of a greedy algorithm. At each step, thealgorithm makes a “greedy” decision <strong>to</strong> merge the two subtrees with least weight.This makes the algorithm simple, but does it give the desired result? This sectionconcludes with a proof that the Huffman tree indeed gives the most efficientarrangement for the set of letters.The proof requires the following lemma.Lemma 5.1 For any Huffman tree built by function buildHuff containing atleast two letters, the two letters with least frequency are s<strong>to</strong>red in siblings nodeswhose depth is at least as deep as any other leaf nodes in the tree.Proof: Call the two letters with least frequency l 1 <strong>and</strong> l 2 . They must be siblingsbecause buildHuff selects them in the first step of the construction process.Assume that l 1 <strong>and</strong> l 2 are not the deepest nodes in the tree. In this case, the Huffmantree must either look as shown in Figure 5.30, or in some sense be symmetrical<strong>to</strong> this. For this situation <strong>to</strong> occur, the parent of l 1 <strong>and</strong> l 2 , labeled V, must havegreater weight than the node labeled X. Otherwise, function buildHuff would

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

Saved successfully!

Ooh no, something went wrong!