I have a recursive function that bypasses some Huffman tree.
I need to get a string that contains all codes of each symbol.
private void BypassLCR(HuffmanTree node, ref string result)
{
if (node.Symbol != '\0')
{
result += string.Format(" -> {0}| ", node.Symbol);
return;
}
string last = result;
result += "0";
BypassLCR(node.Left, ref result);
last += "1";
result += last;
BypassLCR(node.Right, ref result);
}
Property node.Symbol
is '\\0'
by default when the node is not a leaf.
For example, I have a text containing 'r'
, 'o'
, 'b'
and 'a'
symbols. Their codes: 00, 01, 10 and 11 respectively.
Then the output would be:
00 -> r| 01 -> o| 10 -> b| 00 -> r| 01 -> o| 11 -> a|.
I know problem is that last
keeps old data about child subtrees. But where in the code to clear it?
Would this work for you?
private string TraverseLCR(HuffmanTree node, string code)
{
if (IsLeaf(node))
return $"{code} -> {node.Symbol}| ";
var leftSubtreeResult = TraverseLCR(node.Left, code + "0");
var rightSubtreeResult = TraverseLCR(node.Right, code + "1");
return leftSubtreeResult + rightSubtreeResult;
}
private bool IsLeaf(HuffmanTree node) => node.Symbol != '\0';
Usage:
var allCodes = TraverseLCR(treeRoot, string.Empty);
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.