Saving a binary tree to a file

I have an unbalanced (not binary-search) binary tree. I need to pump (and later decode) it into a txt file. How can I do this in an efficient way?

I found a link that talks about a similar (same) problem, but for me this is obvious

+4
source share
1 answer

Take a look at LeetCode .

I like this solution because it is relatively efficient and creates files with easy output.

Assuming you have a tree like this:

    _30_ 
   /    \    
  10    20
 /     /  \ 
50    45  35

This solution allows you to serialize it into such an output text file:

30 10 50 # # # 20 45 # # 35 # #

To do this, it is enough to perform a simple preliminary traversal through the tree:

void writeBinaryTree(BinaryTree *p, ostream &out) {
  if (!p) {
    out << "# ";
  } else {
    out << p->data << " ";
    writeBinaryTree(p->left, out);
    writeBinaryTree(p->right, out);
  }
}

, # node.

, :

void readBinaryTree(BinaryTree *&p, ifstream &fin) {
  int token;
  bool isNumber;
  if (!readNextToken(token, fin, isNumber)) 
    return;
  if (isNumber) {
    p = new BinaryTree(token);
    readBinaryTree(p->left, fin);
    readBinaryTree(p->right, fin);
  }
}

, .

, : node .

, , .

+9

All Articles