-
Notifications
You must be signed in to change notification settings - Fork 3
/
297.cpp
104 lines (97 loc) · 2.86 KB
/
297.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
99
100
101
102
103
104
/**
* 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 {
private:
void _serialize(TreeNode* node, ostringstream& out) {
if (node == nullptr) {
out << "# ";
return;
}
out << node->val << ' ';
_serialize(node->left, out);
_serialize(node->right, out);
}
TreeNode* _deserialize(istringstream& in) {
string token;
in >> token;
if (token == "#") return nullptr;
TreeNode* node = new TreeNode(stoi(token));
node->left = _deserialize(in);
node->right = _deserialize(in);
return node;
}
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);
TreeNode* node = _deserialize(in);
return node;
}
};
// Your Codec object will be instantiated and called as such:
// Codec ser, deser;
// TreeNode* ans = deser.deserialize(ser.serialize(root));
// v2
// /**
// * 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 {
// public:
// // Encodes a tree to a single string.
// void serialize_(TreeNode* node, string& res) {
// if (node == nullptr) {
// res += "R#L";
// return;
// }
// res += "R" + to_string(node->val) + "L";
// serialize_(node->left, res);
// serialize_(node->right, res);
// }
// string serialize(TreeNode* root) {
// string res = "";
// serialize_(root, res);
// return res;
// }
// TreeNode* deserialize_(string& data, int& index) {
// if (index == data.size()) return nullptr;
// index++;
// int start = index;
// while (data[index] != 'L') index++;
// string valStr = data.substr(start, index - start);
// index++;
// if (valStr == "#") return nullptr;
// int val = stoi(valStr);
// TreeNode* node = new TreeNode(val);
// node->left = deserialize_(data, index);
// node->right = deserialize_(data, index);
// return node;
// }
// // Decodes your encoded data to tree.
// TreeNode* deserialize(string data) {
// int index = 0;
// TreeNode* root = deserialize_(data, index);
// return root;
// }
// };
// // Your Codec object will be instantiated and called as such:
// // Codec ser, deser;
// // TreeNode* ans = deser.deserialize(ser.serialize(root));