-
Notifications
You must be signed in to change notification settings - Fork 0
/
449.cpp
48 lines (44 loc) · 1.16 KB
/
449.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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Codec {
void serialize(TreeNode *root, stringstream& in) {
if (root) {
in << root->val << " ";
serialize(root->left, in);
serialize(root->right, in);
} else {
in << "# ";
}
}
TreeNode *deserialize(stringstream& out) {
string s;
out >> s;
if (s == "#") return 0;
TreeNode *node = new TreeNode(stoi(s));
node->left = deserialize(out);
node->right = deserialize(out);
return node;
}
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
stringstream in;
serialize(root, in);
return in.str();
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
stringstream out(data);
return deserialize(out);
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));