-
Notifications
You must be signed in to change notification settings - Fork 73
/
main.cpp
66 lines (58 loc) · 1.28 KB
/
main.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
#include <cstdlib>
#include <iostream>
#include <map>
#include <queue>
#include <sstream>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Codec {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
ostringstream out;
_serialize(root, out);
return out.str();
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
istringstream in(data);
return _deserialize(in);
}
private:
void _serialize(TreeNode* root, ostringstream& out) {
if (root == nullptr) {
out << "$ ";
return;
}
out << root->val << " ";
_serialize(root->left, out);
_serialize(root->right, out);
}
TreeNode* _deserialize(istringstream& in) {
string val;
in >> val;
if (val == "$" || val.empty() ) {
return nullptr;
}
TreeNode* node = new TreeNode(stoi(val));
node->left = _deserialize(in);
node->right = _deserialize(in);
return node;
}
};
int main() {
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
Codec codec;
codec.deserialize(codec.serialize(root));
return 0;
}