// serialize n-ary tree from preorder to post order
public static void serialize(NNode curr, BufferedWriter bw){
if(curr != null){
try{
bw.write(curr.data + " ");
for(NNode node : curr.list){
serialize(node, bw);
}
bw.write("#" + " ");
}catch(IOException e){
}
}
}
public static NNode deserialize(Iterator<String> ite){
if(ite.hasNext()){
String token = ite.next();
if(!token.equals("#")){
NNode node = new NNode(token);
NNode n = deserialize(ite);
if(n != null)
node.list.add(n);
return node;
}else{
return deserialize(ite);
}
}
return null;
}
// deserialize with stack
public static NNode deserializeStack(Iterator<String> ite){
Stack<NNode> stack = new Stack<NNode>();
while(ite.hasNext()){
String token = ite.next();
if(!token.equals("#")){
stack.push(new NNode(token));
}else{
if(stack.size() > 1){
NNode top = stack.pop();
NNode peek = stack.peek();
peek.list.add(top);
}
}
}
return stack.peek();
}
public static void serializeBinary(Node root, BufferedWriter out) {
try {
if(root != null) {
out.write(root.data + " ");
serializeBinary(root.left, out);
serializeBinary(root.right, out);
} else {
out.write("# ");
}
} catch(Exception e) {
System.err.println("Error" + e.getMessage());
}
}
public static Node deserializeIterator(Iterator<String> ite) {
Node root = null;
if(ite.hasNext()) {
String token = ite.next();
if(!token.equals("#")) {
root = new Node(Integer.parseInt(token));
root.left = deserializeIterator(ite);
root.right = deserializeIterator(ite);
}
}
return root;
}