How to build a right bounded Huffman tree (so that the depth of any left child on any node is not larger than the depth on the right child on this node).
I already have a Huffman tree from here . The LeafNode's are the one with the symbols on it and no children and the InternalNode's are the one that have children.
My Idea would be to make a normal Huffman tree first and then sort it. To do this (every symbol should have the same amount of bits afterwards) I would go through the created Huffman tree and sort every Node in one row by their (largest) depth.
Does anyone have a good Idea how to program this in C++ or an easier solution to build a right bounded Huffman tree?
One way to build a right-bounded Huffman tree is to modify the standard Huffman tree building algorithm. Here's one way to do it in C++:
void buildRightBoundedTree(Node* root) {
if (root == nullptr) return;
// Compare the depth of the left and right children
if (root->left->depth > root->right->depth) {
// Swap the children
Node* temp = root->left;
root->left = root->right;
root->right = temp;
}
// Recursively apply the procedure to the children
buildRightBoundedTree(root->left);
buildRightBoundedTree(root->right);
}
Or you could just build the tree that way in the first place. Add a const int d;
to INode
, and construct with INode(int f, int d): f(f), d(d) {}
. Construct Leaf
with LeafNode(int f, char c): INode(f, 0), c(c) {}
. Construct InternalNode
with:
InternalNode(INode* c0, INode* c1) :
INode(c0->f + c1->f, std::max(c0->d, c1->d) + 1),
left(c0->d > c1->d ? c1 : c0), right(c0->d > c1->d ? c0 : c1) {}
By the way, there is bug in the Rosetta Code. It should be:
++frequencies[*(unsigned char *)ptr++];
Otherwise bytes above 127 result in a negative index.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.