Serialization/Deserialization of a binary tree

Design an algorithm and write code to serialize and deserialize a binary tree. Writing the tree to a file is called ‘serialization’ and reading back from the file to reconstruct the exact same binary tree is ‘deserialization’.

Sponsored: has published a chatbot, who can chat with you and help you find apartments in San Francisco and Bay area. Check it out:

01 void treeToFile(Node* head, ofstream& target_file)
02 {
03     if(head==NULL){
04         target_file<<“#”<<” “;
05         return;
06     }
07     target_file<<head->value<<” “;
08     treeToFile(head->left,target_file);
09     treeToFile(head->right,target_file);
10 }
12 Node* fileToTree(ifstream& input_file)
13 {
14     string s;
15     input_file>>s;
16     if(s==“#”)
17         return NULL;
18     while(s==” “)
19         input_file>>s;
20     Node* head=new Node;
21     head->value=atoi(s.c_str());
22     head->left=fileToTree(input_file);
23     head->right=fileToTree(input_file);
24     return head;
25 }
This entry was posted in File operation, Recursive, Tree. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s