-
Notifications
You must be signed in to change notification settings - Fork 3
/
428.cpp
62 lines (56 loc) · 1.4 KB
/
428.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
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val) {
val = _val;
}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
class Codec {
public:
// Encodes a tree to a single string.
void _serialize(Node* node, string& s) {
if (node == nullptr) s.push_back('#');
else {
int value = node->val;
int size = node->children.size();
s += to_string(value) + " " + to_string(size) + " ";
for (auto child : node->children) {
_serialize(child, s);
}
}
}
string serialize(Node* root) {
string s = "";
_serialize(root, s);
return s;
}
Node* _deserialize(stringstream& ss) {
string value;
string size;
ss >> value;
if (value == "#") return nullptr;
Node* node = new Node(stoi(value));
ss >> size;
for (int i = 0; i < stoi(size); i++) {
node->children.push_back(_deserialize(ss));
}
return node;
}
// Decodes your encoded data to tree.
Node* deserialize(string data) {
stringstream ss(data);
return _deserialize(ss);
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));