我遇到了霍夫曼树的问题。我认为我的代码有一个明确的逻辑。我首先构建了一个优先级队列来比较Node的权重,并将Node放在优先级队列顶部的最小权重。
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
struct Node
{
int weight, depth;
Node *left, *right;
Node(int value):weight(value), left(NULL),right(NULL),depth(0){}
Node(int value, Node* left_leaf_ptr, Node* right_leaf_ptr) : weight(value), left(left_leaf_ptr), right(right_leaf_ptr), depth(0) {}
};
//this struct is used for priority queue
struct Greater
{
bool operator () (Node a, Node b){return a.weight > b.weight;}
};
// find whether the node is a leaf
bool isleaf(Node node) { return node.left == NULL && node.right == NULL; }
// update the depth of Huffman Tree
void update_depth(Node& node,int depth)
{
node.depth=depth;
if (! isleaf(node))
{
depth++;
update_depth(*node.left,depth);
update_depth(*node.right, depth);
}
}
Node build_Huffman_tree(priority_queue<Node, vector<Node>, Greater> weights_queue)
{
while (weights_queue.size() > 1)
{
Node l1=weights_queue.top();
weights_queue.pop();
Node l2 = weights_queue.top();
weights_queue.pop();
Node l3(l1.weight + l2.weight, &l1, &l2);
update_depth(l3, 0);
weights_queue.push(l3);
}
return weights_queue.top();
}
int main()
{
priority_queue<Node, vector<Node>, Greater> weights_queue;
weights_queue.push(Node(1));
weights_queue.push(Node(1));
weights_queue.push(Node(3));
weights_queue.push(Node(5));
Node root = build_Huffman_tree(weights_queue);
return 0;
}
当我在C ++ 11中运行该程序时,在函数build_Huffman_tree内的第二个while循环中,它创建了一个权重为2的节点,深度为4700.更糟糕的是,这个节点似乎无穷无尽。即它的左子树有权重2,这个子树的左子树的权重为2,依此类推......
因此,请指出我的程序失败的原因,并教我如何解决它。