-
Notifications
You must be signed in to change notification settings - Fork 0
/
Serialize and Deserialize Binary Tree.cpp
98 lines (91 loc) · 1.83 KB
/
Serialize and Deserialize Binary Tree.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include "tree.h"
string serialize(TreeNode* root)
{
queue<TreeNode*> q;
stringstream ss;
q.push(root);
string s;
if (root==NULL)
return s;
while (!q.empty())
{
TreeNode* tmpnode = q.front();
string tmpstring;
if (tmpnode != NULL)
{
tmpstring = inttostring(tmpnode->val);
s = s + tmpstring + " ";
}
else
{
s = s + "# ";
}
q.pop();
if (tmpnode!=NULL)
{
q.push(tmpnode->left);
q.push(tmpnode->right);
}
}
s.erase(s.end()-1);
while (s[s.size()-1]=='#')
{
s.erase(s.end()-1);
s.erase(s.end()-1);
}
return s;
}
TreeNode* deserialize(string data)
{
if (data.size()==0)
return NULL;
queue<TreeNode*> q;
istringstream ss(data);
vector<string> sv;
int tmp;
do
{
string s;
ss>>s;
sv.push_back(s);
} while(ss);
TreeNode* root = new TreeNode(stringtoint(sv[0]));
q.push(root);
int k=0;
while (k<sv.size()-2)
{
TreeNode* tm = q.front();
q.pop();
if (sv[++k]!="#")
{
tmp = stringtoint(sv[k]);
tm->left = new TreeNode(tmp);
q.push(tm->left);
}
if (k+1<sv.size()-1)
if (sv[++k]!="#")
{
tmp = stringtoint(sv[k]);
tm->right = new TreeNode(tmp);
q.push(tm->right);
}
}
return root;
}
int main()
{
ifstream f("in.txt");
string s;
vector<string> ss;
while (!f.eof())
{
f>>s;
ss.push_back(s);
}
TreeNode* t = buildtree(ss);
string sss = serialize(t);
//cout<<sss<<endl;
TreeNode* tt = deserialize(sss);
//printtree(tt);
return 0;
}