将树数据结构存储在文本文件中以供重用的任何方法


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文件中,假设我有一个字符串"helloworld"。现在我计算了每个字符的频率,然后创建了一个霍夫曼树。现在,我如何将huffman树存储在一个文本文件中,以便在任何其他程序中使用??有什么建议。。

inorderpreorderpostorder遍历中的任何一个存储在文件中,然后使用这两个遍历重建树。

在这里,我考虑了preorderinorder遍历:

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=遍历数组的长度。

相关内容

  • 没有找到相关文章

最新更新