Huffman tree, also known as the optimal tree, is a kind of tree with the shortest length of the weighted path, with the length of the path from the node to the root of the route length and the accumulation of weights on the node.
So how do you build a huffman tree? We need the Huffman algorithm.
1, using the given n weights constitute a set of n binary tree sets F, each binary tree has only a weighted value of the root node, the left and right subtree are empty.
2, choose the tree with the least weight of the root node as the left and right subtree, and reset the weight of the root node of the new two-fork tree as the sum of the right and left subtree weights.
3, delete the two lessons in set F, and add the newly obtained two tree to F.
4, repeat 2, 3 operation until only one subtrees tree is left in F.
such as: Huffman construction process (where the red number represents the weight of the node)
Huffman storage: There is no node in the Huffman tree, a huffman tree with n leaf nodes has 2n-1 nodes, which can be stored in a one-dimensional array of size 2n-1.
Encode a path from the root path to the leaf node, decoding a path from the leaf node to the root, for each node needs to know its Father node and know its left and right child node.
The Huffman tree establishes the main code implementation:
voidCreatetree (Constt* A, size_t size,Constt&Invalid) {assert (a); Heap<node*, nodecompare<t>>minheap;//A small pile of structure for(size_t i =0; i < size; ++i) {if(A[i]! =Invalid) { //build a[i] into a node, insert a heapnode* node =NewNode (A[i]); Minheap.push (node); } } while(Minheap.size () >1{//Get two elements with the smallest weight as left and right subtree Node* left =Minheap.top (); Minheap.pop (); Node* right =Minheap.top (); Minheap.pop (); Using the sum of the weights of the left and right subtree to construct node node.* Parent =NewNode (Left->_weight + right->_weight);
Link to parent->_left =Left ; Parent->_right =Right ; Left->_parent =parent; Right->_parent =parent; Minheap.push (parent); } _root=Minheap.top (); }
Huffman encoding: The Convention left branch represents the character ' 0 ' and the right branch represents the character ' 1 ', then a string consisting of branching characters from the root node to the leaf node is encoded as the leaf knot character
Huffman (Huffman) tree and its application