[LeetCode] Serialize and Deserialize N-ary Tree

428. Serialize and Deserialize N-ary Tree

Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.

Design an algorithm to serialize and deserialize an N-ary tree. An N-ary tree is a rooted tree in which each node has no more than N children. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that an N-ary tree can be serialized to a string and this string can be deserialized to the original tree structure.

For example, you may serialize the following 3-ary tree

as [1 [3[5 6] 2 4]]. Note that this is just an example, you do not necessarily need to follow this format.

Or you can follow LeetCode’s level order traversal serialization format, where each group of children is separated by the null value.

For example, the above tree may be serialized as [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14].

You do not necessarily need to follow the above-suggested formats, there are many more different formats that work so please be creative and come up with different approaches yourself.

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;
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.
string serialize(Node* root) {
if(!root) return "";
string res = to_string(root->val) + ' ';
if(root->children.size()) {
res += '[';
for(auto ch : root->children) res += serialize(ch) + ' ';
res += ']';
}
return res;
}

// Decodes your encoded data to tree.
Node* deserialize(string data) {
if(data.length() == 0) return NULL;
int i = 0;
return deserialize(data,i)[0];
}

vector<Node*> deserialize(string& data, int &i) {
vector<Node*> nodes;
while(i < data.length() and data[i] != ']') {
if(data[i] == '[') nodes.back()->children = deserialize(data,++i);
else if(data[i] == ' ') i++;
else {
nodes.push_back(new Node(parse(data, i)));
}
}
i++;
return nodes;
}

int parse(string& s, int& i) {
int res = 0;
while(i < s.length() and isdigit(s[i])) {
res = res * 10 + (s[i++] & 0b1111);
}
return res;
}
};

// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/16/PS/LeetCode/serialize-and-deserialize-n-ary-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.