typedefstructHNode { int weight; HNode *lchild, *rchild; } *Htree; intgetWPL(Htree root, int len){ //递归实现,对于已经建好的霍夫曼树,求WPL if (root == NULL) return0; else { if (root->lchild == NULL && root->rchild == NULL) //叶节点 return root->weight * len; else { int left = getWPL(root->lchild, len + 1); int right = getWPL(root->rchild, len + 1); return left + right; } } }
2)非递归实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
intgetWPL(int arr[], int n){ //对于未建好的霍夫曼树,直接求其WPL priority_queue<int, vector<int>, greater<int>> huffman; //小根堆 for (int i = 0; i < n; i++) huffman.push(arr[i]); int res = 0; for (int i = 0; i < n-1 ; i++) { int x = huffman.top(); huffman.pop(); int y = huffman.top(); huffman.pop(); int temp = x + y; res += temp; huffman.push(temp); } return res; }