428. Serialize and Deserialize N-ary Tree
Time = O(n), Space = O(n)
Related Questions:
REDO: 297. Serialize and Deserialize Binary Tree
REDO: 449. Serialize and Deserialize BST
/*
// Definition for a Node.
class Node {
public int val;
public List<Node> children;
public Node() {}
public Node(int _val,List<Node> _children) {
val = _val;
children = _children;
}
};
*/
class Codec {
// Encodes a tree to a single string.
public String serialize(Node root) {
if (root == null) {
return "";
}
StringBuilder sb = new StringBuilder();
serializeHelper(root, sb);
return sb.toString();
}
private void serializeHelper(Node root, StringBuilder sb) {
if (root == null) {
sb.append("0").append(",");
return;
}
List<Node> children = root.children;
sb.append(root.val).append(",").append(children.size()).append(",");
for (Node child : children) {
serializeHelper(child, sb);
}
}
// Decodes your encoded data to tree.
public Node deserialize(String data) {
if (data.equals("")) {
return null;
}
Deque<String> queue = new LinkedList<>(Arrays.asList(data.split(",")));
return deserializeHelper(queue);
}
private Node deserializeHelper(Deque<String> queue) {
if (queue.isEmpty()) {
return null;
}
int val = Integer.parseInt(queue.pollFirst());
int size = Integer.parseInt(queue.pollFirst());
Node root = new Node(val, new ArrayList<>());
for (int i = 0; i < size; i++) {
root.children.add(deserializeHelper(queue));
}
return root;
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));