Fork me on GitHub

Serialize and Deserialize N-ary Tree

Description

https://leetcode.com/problems/serialize-and-deserialize-n-ary-tree/

Solution

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
/*
// 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 {
public:

// Encodes a tree to a single string.
string serialize(Node* root) {
string ret;
if (root == NULL) return ret;
helperSerialize(root, ret);
return ret;
}

void helperSerialize(Node* root, string& ret) {
ret += to_string(root->val);
if (root->children.size() == 0) return;
ret += '[';
for(auto& item : root->children) {
helperSerialize(item, ret);
ret += ' ';
}
ret += ']';
return;
}

int extractNumber(string& s, int& index, int size) {
int ret = 0;
while(index < size && (s[index] <= '9' && s[index] >= '0')) {
ret *= 10;
ret += (s[index] - '0');
index += 1;
}
return ret;
}

// Decodes your encoded data to tree.
Node* deserialize(string data) {
Node* ret = NULL;
int index = 0;
int size = data.size();
helperDeserialize(data, ret, index, size);
return ret;
}

void helperDeserialize(string& data, Node*& root, int& index, int size) {
if (index >= size) return;
int val = extractNumber(data, index, size);
root = new Node(val, vector<Node*>());

if (index == size || data[index] != '[') return;
index += 1; //Skip the '['

while (index < size && data[index]!= ']') {
root->children.push_back(NULL);
helperDeserialize(data, root->children.back(), index, size);
index += 1; //Skip the whitespace
}
index += 1; //Skip the ']'
}
};

// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));