Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving a Binary tree to a file [closed]

I have a non-balanced (not binary-search) binary tree Need to incode (and later decode) it to txt file. How can I do it in efficient way?

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

like image 294
Yakov Avatar asked Nov 15 '13 16:11

Yakov


People also ask

What happens when a binary tree is completed?

A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible.

How to store binary tree in database?

What you must determine is the the order to insert based on the tree's maximum height. The maximum height for a binary tree would be (LN(number of nodes) / LN(2)) + 1 . You should create the tree first and then fill in the ids to associate to each node.


1 Answers

Please look at this on LeetCode.

I like this solution because it's relatively efficient and produces light output files.

Assuming that you've got a tree like this:

    _30_ 
   /    \    
  10    20
 /     /  \ 
50    45  35

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

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

To do this it's enough to perform simple pre-order 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);
  }
}

As you can see, a # symbol is used to represent the null node.

To deserialize this string into a tree you can use:

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);
  }
}

As I said before, this method produces a lightweight representation of Binary Tree.

Of course it has one serious drawback: it requires a symbol to represent the null node.

It can cause potential problems if the nodes of tree are strings that can contain this symbol itself.

like image 157
Zegar Avatar answered Oct 19 '22 23:10

Zegar