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]]. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.
Note:
N is in the range of [1, 1000]
Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.
方法1: recursion
思路:
和297的区别主要在于紫薯的数量不确定,所以在对children序列化之前,先保存一下children.size()。主体仍是dfs,这里采用先序遍历,由于每个节点相当于多了一个后缀的数字来标示它有多少个子节点,这样可以提前创建。注意处理nullptr的问题,一般情况下nullptr不应该被放进children,但也可能出现,如果扩张了children的size但是却没有录入相应的字符标记,而是直接返回,会造成deserialize失败。而且test case里面有根节点直接是null的情况,所以对于null还是要特殊处理一下的。这里采用“#”来标记出现了# 的情况,读到的时候也会知道后面没有size的存在。
/*
// 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 code = "";
serializeHelper(root, code);
return code;
}
void serializeHelper(Node* root, string & code) {
if (!root) {
code += "#";
return;
}
code += to_string(root -> val) + " " + to_string(root -> children.size()) + " ";
for (auto c: root -> children) serializeHelper(c, code);
return;
}
// Decodes your encoded data to tree.
Node* deserialize(string data) {
istringstream in(data);
return deserializeHelper(in);
}
Node* deserializeHelper(istringstream & in) {
string tmp;
in >> tmp;
if (tmp == "#") return nullptr;
int val = stoi(tmp);
in >> tmp;
int n = stoi(tmp);
Node* root = new Node(val, vector<Node*>(n));
for (int i = 0; i < n; i++) {
root -> children[i] = deserializeHelper(in);
}
return root;
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));