Creation of Huffman tree (optimal binary tree)

Source: Internet
Author: User

Huffman Tree is a special binary tree with the least weighted path, so it is also called the optimal binary tree.
Here we do not discuss the basic concepts such as how to calculate paths, but only focus on the creation of trees, the specific process let us for example.

The basic principle is that all nodes are considered as forests at the beginning, each time from the forest to select two root node weight of the smallest tree merged into a new tree, the new tree root node size of two sub-node size and the new tree to rejoin the forest.
As a result, each round of operations can be simplified to two basic operations: merging two trees, inserting a new tree, until only one tree is left in the forest, the Huffman tree.

The weights for 7 nodes are 1 3 7 9 12 18 25, respectively.
First steps to create: Merge 1, 3, add 4

Second step to create: Merge 4, 7, add 11

Third step to create: Merge 9, 11, add 20

Fourth Step created: Merge 12, 18, add 30

Fifth Step created: Merge 20, 25, add 45

Merge the last two trees and get Huffman tree

In the program we actually run to create this tree, the result of the first order traversal is as follows:

You can see that all actions are consistent with the results

During the process of creation, it is important to merge the two trees that have the smallest node weights from the forest each time, and then insert them into the forest, which we can do with the insertion and deletion of the largest minimum heap, and the implementation and explanation of the maximum minimum heap can be seen by my guest:
http://blog.csdn.net/ava1anche/article/details/46965675

Here are the specific code and comments, part of the operation does not explain, look at the comments on the line

/ * Time: 2015.7.20 name: Huffman tree Operation: Huffman tree creation, Huffman Tree sequence traversal (easy to see), Huffman Tree related operations (maximum minimum heap operation), the tree of the middle sequence traversal brief description: Through a Huffman tree forest to create Huffman tree, Each time the tree is built, it removes two trees from the forest, then joins a new tree, in order to make the join and delete more efficient, the forest is implemented by the largest minimum heap. */#include <iostream>usingnamespaceStdintCost =0; constintMax_capacity =100000;//maximum capacity of the forestEnum Type{maxiumn,miniumn};//Represents the type of forest from big to small or from small to largetypedef struct NODE//The structure of the node of the tree{intWeight//define weightsNode* Leftchild;//define left sub-treenode* Rightchild;//define right sub-tree}; Node Flag;//The first sentinel node of a foresttypedef struct HUFFMANTREE//Haffman structure{int size;//The current size of the forestNode*tree[Max_capacity];//maximum capacity of the forest}; Huffmantree Trees;//Huffman trees in the forestvoid Insertmax (node* insertnode)//insertion of forests from large to small (maximum heap insertion){intpos = ++trees.size;//Use the temporary variable to point to the end, and the overall capacity plus one;     for(; Trees.tree[pos/2]->weight < insertnode->weight; POS/=2)//each time the corresponding parent node is compared, look for the insertion position{Trees.tree[pos] = Trees.tree[pos/2];///Do not conform to insert condition to sink corresponding parent node} Trees.tree[pos] = Insertnode;//Find insertion position after inserting}void insertmin (node* insertnode)insertion of forest from small to large (minimum heap insertion){intpos = ++trees.size;//Use the temporary variable to point to the end, and the overall capacity plus one;     for(; Trees.tree[pos/2]->weight>insertnode->weight; POS/=2) {Trees.tree[pos] = Trees.tree[pos/2];///Do not conform to insert condition to sink corresponding parent node} Trees.tree[pos] = Insertnode;//Find insertion position after inserting}node* Deletemax ()//delete of the forest arranged from large to small (delete of maximum heap){int Parent=1, child =1;//For cursors that point to parent nodes and child nodesnode* Maxnode = trees.tree[1];//To save the largest node for deletionnode* lastnode = trees.tree[trees.size];//To save the last node--trees.size;//Quantity minus one     for(Parent=1;Parent*2<= Trees.size;Parent= child) {child =Parent*2;if(Child! = Trees.size)//Prevent cross-border        if(Trees.tree[child]->weight < Trees.tree[child +1]->weight)//Select a larger child node++child;//Every time you need to determine whether the child node has child nodes, not the words on the float save the last node for the complement        if(Lastnode->weight <= trees.tree[Parent]->weight)//This represents the need to ascend the last node for the complement, Loop end        if(Lastnode->weight>trees.tree[child]->weight) Break;Elsetrees.tree[Parent] = Trees.tree[child];//Floating a larger node} trees.tree[Parent] = Lastnode;returnMaxnode;} node* Deletemin ()deletion of forest from small to large (minimum heap deletion){int Parent=1, child =1;//For cursors that point to parent nodes and child nodesnode* Minnode = trees.tree[1];//To save the minimum node for deletionnode* lastnode = trees.tree[trees.size];//To save the last node--trees.size;//Quantity minus one     for(Parent=1;Parent*2<= Trees.size;Parent= child) {child =Parent*2;if(Child! = Trees.size)//Prevent cross-border        if(Trees.tree[child]->weight > Trees.tree[child +1]->weight)//Select a smaller child node++child;//Every time you need to determine whether the child node has child nodes, not the words on the float save the last node for the complement        if(Lastnode->weight >= trees.tree[Parent]->weight)//This represents the need to ascend the last node for the complement, Loop end        if(Lastnode->weight<trees.tree[child]->weight) Break;Elsetrees.tree[Parent] = Trees.tree[child];//Float smaller nodes} trees.tree[Parent] = Lastnode;returnMinnode;}intIsfull ()//Determine if the forest is full{if(Trees.size= = max_capacity)return 1;Else        return 0;}intIsEmpty ()//Determine if the forest is empty{if(Trees.size==0)return 1;Else        return 0;} node* createtree_a ()//Create Tree{ while(Trees.size!=1)//Until only one tree is left{node* one = Deletemin ();//Delete Two trees at a time and merge them into a new treenode* = Deletemin ();        node* newnode=new Node ();        Newnode->weight = One->weight + two->weight;        newnode->leftchild=one;        Newnode->rightchild = both;    Insertmin (NewNode); }returntrees.tree[1];} void Pretraversal (node* root) {cout << root->weight <<"';if(root->leftchild!=null) pretraversal (root->leftchild);if(root->rightchild!=null) pretraversal (root->rightchild);}intMain () {//Main function part is the test code, can ignore    intN Node*flag= new Node (); Node*hufftree=null; Flag->weight =- +;    Flag->leftchild = NULL;    Flag->rightchild = NULL; Trees.size=0; trees.tree[0] = flag; Cin >> N; for(inti =0; i < N;        i++) {node* newnode=new Node ();        CIN >> newnode->weight;        Newnode->leftchild = NULL;        Newnode->rightchild = NULL; Insertmin (NewNode);//Insert Small Gan        //insertmax (newnode);} pretraversal (Createtree_a ());return 0;}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Creation of Huffman tree (optimal binary tree)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.