[英]How to create a right bounded tree from a normal tree in C++ (Huffman)?
如何構建右有界霍夫曼樹(使得任意節點上任意左子節點的深度不大於該節點上右子節點的深度)。
我已經從這里得到了一棵霍夫曼樹。 LeafNode 是帶有符號但沒有子節點的節點,而 InternalNode 是有子節點的節點。
我的想法是先制作一棵普通的哈夫曼樹,然后對其進行排序。 為此(每個符號之后應該具有相同數量的位數)我將通過創建的霍夫曼樹 go 並按它們的(最大)深度對一行中的每個節點進行排序。
有沒有人知道如何在 C++ 中對此進行編程或更簡單的解決方案來構建右有界霍夫曼樹?
構建右界哈夫曼樹的一種方法是修改標准哈夫曼樹構建算法。 這是在 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);
}
或者您可以首先以這種方式構建樹。 添加一個const int d;
到INode
,並用INode(int f, int d): f(f), d(d) {}
構造。 用LeafNode(int f, char c): INode(f, 0), c(c) {}
構造Leaf
。 構造InternalNode
有:
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) {}
順便說一句,Rosetta Code 中有錯誤。 它應該是:
++frequencies[*(unsigned char *)ptr++];
否則超過 127 的字節會導致負索引。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.