Optimal Binary Tree

Source: Internet
Author: User
Tree path length the tree path length is the sum of the path lengths from the root to each node in the tree. In a binary tree with the same number of nodes, the path length of the Complete Binary Tree is the shortest. Weight of the weighted path length of tree (WPL) node of the tree: in some applications, assign a meaningful real number to the node in the tree and the length of the weighted path of the node: the length of the path from the node to the root of the tree and the length of the weighted path (WPL) of the product tree on the node ): it is defined as the sum of the weighted path lengths of all nodes in the tree. The optimal binary tree has the right to W1, W2 ,..., n of WN Leaf nodeAmong all the binary trees, the binary tree with the minimum length of the weight path (that is, the minimum cost) becomes the optimal binary tree. Note:
  • When the weights on the leaves are the same, the full binary tree must be the optimal binary tree. Otherwise, the full binary tree is not necessarily the optimal binary tree.
  • In the optimal binary tree, the higher the weight, the closer the leaf node to the root.
  • The form of the optimal binary tree is not unique, and the WPL is the smallest.

Construct the optimal binary tree Harman Algorithm

  1. Based on the given n weights W1, W2 ,..., wn: Forest F = {T1, T2 ,.., tn}, where each binary tree TI has only one root node with the weight of Wi, and its left and right subtree are empty.
  2. In forest F, select the two trees with the smallest root node weight (when there are more than two trees, you can choose two from them), and name the two trees and a new one, to ensure that the new tree is still a binary tree, you need to add a new node as the root of the new tree and use the selected two trees as the left and right children of the new tree, use the sum of the weights of the two children as the weights of the new roots.
  3. Repeat 2 for the New Forest F until there is only one tree left in the forest F.

Note:

  • N binary trees in the initial forest, each of which has an isolated node, both root and leaf
  • The Harman tree with N leaf nodes needs to be merged n-1 times to generate n-1 new nodes. There are 2-1 knots in the final Heman tree.
  • A strict binary tree does not have a branch node with a level of 1

Storage Structure

#include <stdio.h>#include <stdlib.h>#include <string.h>#define MAX_SIZE 100#define MIN_NUM 1000000struct hfmcode{int weight;int lchild;int rchild;int parent;};

Note:

  1. Therefore, the lower bound of the array is 0, so-1 indicates a null pointer. When the lchild, rchild, and parent values of a node in the tree are not-1, they are the subscript of the left, right, and parent nodes of the node in the vector.
  2. The role of the parent field: it is easier to search for parent nodes. The second is to identify whether the parent value is-1 to distinguish between the root node and the non-root node.

Implement code (1) initialization, set the three pointers in the 2n-1 nodes in T [0 .. s-1] to null (=-1) and the weight to 0.

void initHuffmantree(struct hfmcode *tree, int len){int i;for(i = 0; i < len; i ++){tree[i].weight = 0;tree[i].lchild = -1;tree[i].rchild = -1;tree[i].parent = -1;}}

(2) input: Read the weights of N leaves in the first N components of the vector (T [0 .. n-1.

Int main () {int n, m, I; struct hfmcode hfmtree [max_size]; while (scanf ("% d", & N )! = EOF) {/* Total Number of knots in the Harman tree */m = 2 * n-1;/* initialize the Harman tree */inithuffmantree (hfmtree, M ); /* assign permissions */for (I = 0; I <n; I ++) {scanf ("% d", & hfmtree [I]. weight);}/* construct a Harman tree */createhuffmantree (hfmtree, n, m); printf ("% d \ n", hfmtree [m-1]. weight);} return 0 ;}

(3) Merge the trees in the forest for a total of n-1 times, and the newly generated nodes are sequentially placed in the I component of the vector T (n <= I <= s-1 ). each merge is divided into two steps:

  1. In the current forest T [0 .. in all the nodes of the I-1, t [P1] and T [P2] are selected as the merging objects, where 0 <= p1, p2 <= I-1
  2. Combine the two trees whose root is t [P1] and T [P2] As left and right subtree into a new tree. The new root is the new node T [I]. the specific operation is: Set the parent of T [P1] and T [P2] to I, set the lchild and rchild of T [I] to the sum of the weights of T [P1] and T [P2] of the new node T [I.
  3. After merging, t [P1] and T [P2] are no longer the root in the current forest, because their parent pointers all point to T [I], therefore, the next merge will not be selected as the merged object.
Void createhuffmantree (struct hfmcode * tree, int N, int m) {int M1, M2, I, loc1, loc2, K; for (I = N; I <m; I ++) {/* minimum initial value, minimum number of times */M1 = m2 = min_num; loc1 = loc2 =-1; /* search for the smallest two trees with the minimum weight in a node that has not yet constructed a binary tree */For (k = 0; k <I; k ++) {If (tree [K]. parent =-1) {If (tree [K]. weight <M1) {m2 = m1; loc2 = loc1; M1 = tree [K]. weight; loc1 = K;} else if (tree [K]. weight <m2) {m2 = tree [K]. weight; loc2 = K ;}}/ * modify the parents of two small weight nodes */tree [loc1]. parent = I; tree [loc2]. parent = I;/* modify the weight of the parent */tree [I]. weight = tree [loc1]. weight + tree [loc2]. weight;/* modify the child of the parent */tree [I]. lchild = loc1; tree [I]. rchild = loc2 ;}}
The process of coding and decoding data is encoded. Convert each character in the file into a unique binary string and decompress the data to decode it. To encode a character prefix corresponding to a binary string conversion character set, the encoding of any character in the character set is not the prefix of the encoding of other characters, this encoding becomes the optimal prefix encoding by means of the average length of the prefix encoding or the smallest prefix of the total length of the file. The optimal prefix encoding also has the best compression effect on the file. Harman encoding is the optimal prefix encoding.
  1. The code length of each leaf character Ci is exactly the path length Li from the root to the leaf. The average code length (or file length) is the weighted path length WPL of the binary tree. while the Harman tree is the smallest Binary Tree in WPL, the average coding length is also the smallest.
  2. No leaf in a tree is the ancestor of another leaf. The codes corresponding to each leaf cannot be the prefixes of other leaf codes.

The following describes the implementation process of the harfman encoding algorithm after the harfman tree of a given character set is generated: The leaf T [I] (0 <= I <n) is used as the starting point, go up to the root. Go up to the left branch to generate code 0. Go to the right branch to generate Code 1. note:

  • Because of the encoding and the required reverse encoding order

Algorithm code

/* Harman encoding */struct HFMD {char code [max_size] ;};

Void createhuffmancode (struct hfmcode * htree, struct HFMD * hcode, int N) {/* C and P indicate the locations of children and parents in T */int p, I, C; /* temporary storage encoding */Char CD [N];/* indicates the starting position of the encoding in the CD */INT start; /* perform the encoding of leaf T [I] in sequence */for (I = 0; I <n; I ++) {c = I; Start = N; memset (CD, 0, sizeof (CD); P = htree [C]. parent; while (P! =-1) {CD [-- start] = (htree [p]. lchild = c )? '0': '1'; C = P; P = htree [p]. parent;} strcpy (hcode [I]. Code, CD + start );}}
The linked list is implemented in the table store. If you use the linked list to implement the table store in the table store, you 'd better pay attention to the differences between pointer variables and node variables! Definition of the storage structure of the user tree
// The Harman node type definition struct huffmancode {int power; struct huffmancode * lchild; struct huffmancode * rchild; struct huffmancode * Next ;};

There is a skill in building a Harman tree. It ensures that the linked list is ordered when you build a linked list. In this way, each time you take the smallest two nodes, you only need to retrieve PL = head-> next from the first node head, PR = head-> next, save the sorting time!

/*** Description: Build a user-defined tree */struct huffmancode * createhuffmantree (int n, int * weight) {int I; struct huffmancode * head, * PL, * PR, * proot; head = (struct huffmancode *) malloc (sizeof (struct huffmancode); head-> next = NULL; // initialize the forest for (I = 0; I <N; I ++) {struct huffmancode * pnode = (struct huffmancode *) malloc (sizeof (struct huffmancode); pnode-> power = * (weight + I ); pnode-> lchild = pnode-> rchild = pnode-> N EXT = NULL; addnode (Head, pnode);} // construct the while (Head-> next) of the Harman tree {// If (! Head-> next) {break;} // extracts the smallest two points of the node from the single-chain table, PL = head-> next; Pr = pl-> next; // Delete the PL and PR nodes, and add them to the head tree-> next = Pr-> next; proot = (struct huffmancode *) malloc (sizeof (struct huffmancode )); proot-> power = pl-> power + Pr-> power; proot-> lchild = pl; proot-> rchild = Pr; addnode (Head, proot );} return head-> next;}/*** Description: Add node */void addnode (struct huffmancode * head, struct huffmancode * pnode) {struct huffmancode * t = head; // find the node with the first weight greater than the given node, t specifies the previous node of the node while (t-> next & T-> next-> power <pnode-> power) {T = T-> next ;} pnode-> next = T-> next; t-> next = pnode ;}

Obtain WPL

/*** Description: Obtain the length of the weighted path of the Haffman tree (initial level: 0) */INT getwpl (struct huffmancode * root, int level) {If (! Root) {return 0;} If (! Root-> lchild &&! Root-> rchild) {return root-> power * level;} return getwpl (root-> lchild, level + 1) + getwpl (root-> rchild, LEVEL + 1 );}
Clear the Harman tree
/*** Description: Clear the Harman tree */void freehuffmantree (struct huffmancode * root) {If (! Root) {return;} freehuffmantree (root-> lchild); freehuffmantree (root-> rchild); free (Root );}

PostscriptThe basis of the optimal solution is that of the two. I have posted a nine-degree ACM question below to practice the problem. I think it is good to comment on it. If you have any questions, I can discuss it!

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.