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
classNode {
publicint val;
public List<Node> children;
publicNode() {}
publicNode(int _val,List<Node> _children) {
val = _val;
children = _children;
}
};
classCodec {
// Encodes a tree to a single string.public String serialize(Node root) {
}
// Decodes your encoded data to tree.public Node deserialize(String data) {
}
}
// Your Codec object will be instantiated and called as such:// Codec codec = new Codec();// codec.deserialize(codec.serialize(root));
In an n-ary tree, there is no designated left or right child. We can store an ‘end of children’ marker with every node. The following diagram shows serialization where ] is used as end of children marker.
classCodec {
// Encodes a tree to a single string.public String serialize(Node root) {
if (root ==null) {
return"";
}
StringBuilder sb =new StringBuilder();
sb.append(root.val);
sb.append("[");
for (Node child : root.children) {
sb.append(serialize(child));
}
sb.append("]");
return sb.toString();
}
// Decodes your encoded data to tree.public Node deserialize(String data) {
Node root =null;
Stack<Node> stack =new Stack<>();
int i = 0;
while (i < data.length()) {
int start = i;
// Move pointer forward until we don't find a digit...while (i < data.length() && Character.isDigit(data.charAt(i))) {
i++;
}
// If we haven't found a digit then we must have found the end of a child list...if (start == i) {
Node child = stack.pop();
if (stack.isEmpty()) {
root = child;
break;
} else {
// Remove the child from the stack and assign it to the previous node on the stack stack.peek().children.add(child);
}
} else {
Node n =new Node();
n.val= Integer.parseInt(data.substring(start, i));
n.children=new ArrayList<>();
stack.push(n);
}
i++;
}
return root;
}
}