-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsoln.cpp
66 lines (56 loc) · 1.44 KB
/
soln.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
/*
// Definition for a Node.
class Node {
public:
int val = NULL;
vector<Node*> children;
Node() {}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
class Codec {
private:
void preorder(Node * node, string & data) {
if (node != nullptr) {
data += " " + to_string(node->val);
for(Node* child : node->children) {
preorder(child, data);
}
data += " #";
}
}
void build(Node * root, istringstream & iss) {
string token;
while (iss >> token) {
if (token == "#") {
break;
}
Node * child = new Node(stoi(token), {});
root->children.push_back(child);
build(child, iss);
}
}
public:
// Encodes a tree to a single string.
string serialize(Node* root) {
string data = "";
preorder(root, data);
return data.empty() ? data : data.substr(1);
}
// Decodes your encoded data to tree.
Node* deserialize(string data) {
if (data.empty()) return nullptr;
istringstream iss(data);
string val;
iss >> val;
Node * root = new Node(stoi(val), {});
build(root, iss);
return root;
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));