#include <string>
#include <vector>
#include <iostream>
#include <sstream>
using namespace std;
struct BTNode{
int val;
BTNode *left;
BTNode *right;
BTNode(int v): val(v),left(NULL),right(NULL){}
};
void serialize(BTNode *root, stringstream& sstr){
int i = 0;
if(!root){
sstr<< "# ";
return;
}
sstr << root -> val << " ";
serialize(root->left, sstr);
serialize(root->right, sstr);
}
BTNode* deserialize(stringstream& sstr){
string c;
sstr >> c;
if(c == "#") return NULL;
BTNode *root = new BTNode(stoi(c));
root->left = deserialize(sstr);
root->right = deserialize(sstr);
return root;
}
int main(){
BTNode *root = new BTNode (0);
root->left = new BTNode (0);
root->right = new BTNode (0);
root->left->left = new BTNode (1);
root->left->right = new BTNode (2);
root->right->left = new BTNode (3);
root->right->right = new BTNode (4);
stringstream sstr1;
serialize(root, sstr1);
cout << sstr1.str()<<endl;
BTNode *newroot = deserialize(sstr1);
stringstream sstr2;
serialize(newroot, sstr2);
cout<< sstr2.str()<<endl;
getchar();
return 0;
}
Result:
No comments:
Post a Comment