abstract class HuffmanTree1 implements Comparable<HuffmanTree1>
{
public final int frequency;
public HuffmanTree1(int freq)
{
frequency = freq;
}
public int compareTo(HuffmanTree1 tree)
{
return frequency - tree.frequency;
}
}
class HuffmanLeaf1 extends HuffmanTree1
{
public final char value;
public HuffmanLeaf1(int freq, char val)
{
super(freq);
value = val;
}
}
class HuffmanNode1 extends HuffmanTree1
{
public final HuffmanTree1 left, right;
public HuffmanNode1(HuffmanTree1 l, HuffmanTree1 r)
{
super(l.frequency + r.frequency);
left = l;
right = r;
}
}
public class SimpleHuffmanCode
{
static int ctr=0;
static String[] s=new String[50];
public static HuffmanTree1 buildTree(int[] charFreqs)
{
PriorityQueue<HuffmanTree1> trees = new PriorityQueue<HuffmanTree1>();
for (int i = 0; i < charFreqs.length; i++)
if (charFreqs[i] > 0)
trees.offer(new HuffmanLeaf1(charFreqs[i], (char)i));
assert trees.size() > 0;
while (trees.size() > 1)
{
HuffmanTree1 a = trees.poll();
HuffmanTree1 b = trees.poll();
trees.offer(new HuffmanNode1(a, b));
}
return trees.poll();
}
public static void main(String[] args) throws IOException
{
File file = new File("test.txt");
int c[]=count_freq(file);
HuffmanTree1 tree = buildTree(c);
}
在test.txt文件中假设我有一个字符串&#34; hello world&#34;。现在我已经计算了每个角色的频率,然后创建了一个霍夫曼树。现在我如何在一个文本文件中存储thr霍夫曼树,以便在任何其他程序中使用?任何建议..
答案 0 :(得分:1)
将inorder
和preorder
或postorder
遍历中的任意一个存储在文件中,然后使用2次遍历重建树。
我在这里考虑了preorder
和inorder
遍历:
struct node* buildTree(char in[], char pre[], int inStrt, int inEnd)
{
static int preIndex = 0;
if(inStrt > inEnd)
return NULL;
/* Pick current node from Preorder traversal using preIndex
and increment preIndex */
struct node *tNode = newNode(pre[preIndex++]);
/* If this node has no children then return */
if(inStrt == inEnd)
return tNode;
/* Else find the index of this node in Inorder traversal */
int inIndex = search(in, inStrt, inEnd, tNode->data);
/* Using index in Inorder traversal, construct left and
right subtress */
tNode->left = buildTree(in, pre, inStrt, inIndex-1);
tNode->right = buildTree(in, pre, inIndex+1, inEnd);
return tNode;
}
使用struct node *root = buildTree(in, pre, 0, len - 1);
调用,其中len =遍历数组的长度。