E
E
Evgeny Trofimov2016-05-22 14:13:08
Programming
Evgeny Trofimov, 2016-05-22 14:13:08

How to write/read a tree from a file?

I am writing an algorithm for compressing a text document using the Huffman and Shannon-Fano methods.
Almost everything is ready - that is, a tree is created, codes for each character are created from it, and the text is encoded with their help.
It remains only to somehow write down and read the tree, according to which it will be possible to decrypt the message ..
Here is the structure for Shannon-Fano:

struct spisok//список
{
  char ch;//символ
  string code;//код
  double k;//вероятность
  spisok *next;
}*myspisok=NULL;

struct tree //дерево
{
  tree *left,*right;
  spisok *s;//содержит в себе список
}*mytree=NULL;

Let me explain - each element of the tree has a list, for a leaf this list consists of only one element, and that is what is needed.
In fact, you can generally delete all lists except the list near the tree.
The structure for Huffman seems to be simpler -
struct spisok { //список деревьев FailFish
  char simvol;
  string code;
  int kol;
  spisok *next;
  spisok *prev;
  spisok *left;
  spisok *right;
}*head,*sortlist,*tree;

Here *next and *prev are not needed, you need to write, as I think, only simvol,*left,*right
How can this be done?
I have a tree decryption function like this -
for(int i=0;i<final_code.length();i++) 
  {
    if (k==size)//как только количество символов в расшифрованном файле будет равно количеству символов в исходном
    {
      break;
    }
    if (t->left == NULL && t->right == NULL)//дошли до листа
    {
      fwrite(&(t->s->ch),sizeof(char),1,decrypted);//записываем символ из листа
      cout<<t->s->ch;//выводим его 
      t=head;//поднимаемся назад к голове
      k++;
    }
    if (final_code[i]=='1') t=t->right;//если 1 - идем вправо
    else t=t->left;//иначе - влево
  }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
AtomKrieg, 2016-05-22
@deadrime

www.geeksforgeeks.org/serialize-deserialize-binary-tree
Personally, I don't use pointers for trees for a long time, but I write nodes in std::vector and instead of pointers - an index to an array element. Serializing a vector is easy.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question