-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcodecNTree.cpp
More file actions
38 lines (34 loc) · 1017 Bytes
/
codecNTree.cpp
File metadata and controls
38 lines (34 loc) · 1017 Bytes
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
class Codec {
public:
// Encodes a tree to a single string.
string serialize(Node* root) {
string res;
serializeHelper(root, res);
return res;
}
void serializeHelper(Node* node, string& res) {
if (!node) res += "#";
else {
res += to_string(node->val) + " " + to_string(node->children.size()) + " ";
for (auto child : node->children) {
serializeHelper(child, res);
}
}
}
// Decodes your encoded data to tree.
Node* deserialize(string data) {
istringstream iss(data);
return deserializeHelper(iss);
}
Node* deserializeHelper(istringstream& iss) {
string val = "", size = "";
iss >> val;
if (val == "#") return NULL;
iss >> size;
Node *node = new Node(stoi(val), {});
for (int i = 0; i < stoi(size); ++i) {
node->children.push_back(deserializeHelper(iss));
}
return node;
}
};