Pre-Knowledge:
path : A path from one node in the tree to another, and the number of branches on the path becomes the length of the route;
the path length of the tree : the sum of the length of the path from the root to each leaf;
The belt-weighted path length of a node: the product of the path length from the node to the root of the tree and the value of the node.
the length of the weighted path of the tree : The sum of the weighted path length of all leaf nodes;
Any two binary trees with the same structure, because their leaf node weights may be different, so their path length will be different; Huffman tree refers to the two-tree with the smallest length of the weighted path;
How to construct Huffman tree:
Suppose there is a set of weights {5,29,7,8,14,23,3,11}, we will use this set of weights to demonstrate the process of constructing Huffman tree.
The first step: to construct a forest with 8 trees with the weights of the 8 weights of the seat root node;
The second step: choose two root of the smallest weight of the tree 3, 5 seats left and right sub-tree to form a new tree, the new root node of the weight of 3+5, and the two trees removed from the forest, and the new tree added;
Step three: Repeat the second step until there is only one tree in the forest, select 7,8 here;
Fourth Step:
Fifth Step:
Sixth step:
Seventh Step:
Huffman Code:
In Huffman tree, there are only nodes with leaf node and degree 2. Number of leaf nodes = +1 of nodes with degrees 2.
Optimal binary tree (Huffman tree)