-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path297. Serialize and Deserialize Binary Tree.cpp
53 lines (50 loc) · 1.23 KB
/
297. 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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
#include<sstream>
class Codec {
public:
void helper(TreeNode* root , stringstream &out )
{
if( !root)
{
out<<"x ";
return;
}
out<< root->val<<" ";
helper(root->left, out);
helper(root->right, out);
}
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
stringstream out;
helper(root, out);
cout<<out.str();
return out.str();
}
TreeNode* helper2( stringstream &in)
{
string val;
in>> val;
if( val== "x")
return NULL;
TreeNode* root = new TreeNode(stoi(val));
root->left= helper2(in);
root->right = helper2(in);
return root;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
stringstream in(data);
return helper2(in);
}
};
// Your Codec object will be instantiated and called as such:
// Codec ser, deser;
// TreeNode* ans = deser.deserialize(ser.serialize(root));