Design an algorithm and write code to serialize and deserialize 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'.
Solution:
// TreeSerialAndDeserial.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <fstream>
#include <string>
#include <iostream>
using namespace std;
class Tree
{
public:
Tree(Tree* left, Tree* right, int val);
Tree* setLeft(Tree* node, Tree* left) {node->left = left;}
Tree* setRight(Tree* node, Tree* right) {node->right = right;}
Tree* getLeft(Tree* node) {return node->left;}
Tree* getRight(Tree* node) {return node->right;}
void setVal(Tree* node, int val) {node->val = val;}
int getVal(Tree* node) {return node->val;}
void deserialize(Tree*& tree,string path); // from file to tree, not serialize
void serialize(Tree* tree, const string& path); // from tree to file, serialize(plain storage)
void insertNode(Tree* tree,Tree* node);
private:
Tree* left;
Tree* right;
int val;
}; //dont forget ";" here
Tree::Tree(Tree* left, Tree* right, int val)
{
this->left = left;
this->right = right;
this->val = val;
}
void Tree::insertNode(Tree* tree,Tree* node)
{
Tree* tree_prt = tree;
bool flag = false;
if(tree == NULL)
return;
else
{
while(tree)
{
if(tree->val > node->val)
{
tree_prt = tree;
tree = tree->left;
flag = true;
}
else
{
tree_prt = tree;
tree = tree->right;
}
}
tree = node;
if(flag) tree_prt->left = tree;
else tree_prt->right = tree ;
}
}
void Tree::deserialize(Tree*& tree,string path)
{
ifstream ifile;
ifile.open(path,std::ifstream::in);
int temp = 0;
while(ifile >> temp )
{
if(!tree)
{
tree = new Tree(NULL, NULL, temp);
}
else
{
Tree* node = new Tree(NULL, NULL, temp);
insertNode(tree,node);
}
}
}
void Tree::serialize(Tree* tree,const string& path) //preorder tree, easiest way to do this
{
ofstream ofile;
if(!ofile.is_open())
{
ofile.open(path,std::ofstream::out);
}
if(!tree)
return;
else
{
ofile << tree->val;
serialize(tree->left,path);
serialize(tree->right,path);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
Tree* tree = NULL;
tree->deserialize(tree,"c:/out.txt");
tree->serialize(tree,"c:/in.txt");
return 0;
}
浙公网安备 33010602011771号