iniyansparkle
BAN USERpackage algos;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Queue;
/**
* Created by paramasivami on 4/10/16.
*/
public class SerializeTree {
//Tree Node.
public static class Node{
private int data;
//Set of children.
private List<Node> children;
public Node(){
this.children = new ArrayList<>();
}
public Node(int data){
this.data = data;
this.children = new ArrayList<>();
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public List<Node> getChildren() {
return children;
}
public void setChildren(List<Node> children) {
this.children = children;
}
public void addChildrenNode(Node child){
this.children.add(child);
}
}
public static StringBuffer traversal(StringBuffer s, Node root){
if(root.getChildren().size() == 0) {
s.append(String.valueOf(root.data)).append(",");
s.append("#").append(",");
}
else{
s.append(String.valueOf(root.data)).append(",");
root.children.forEach(
child -> traversal(s, child)
);
}
return s;
}
public static Node constructTree(Queue queue, Node result){
String s = (String) queue.remove();
if(!s.equals("#")){
result = new Node(Integer.parseInt(s));
Node n = constructTree(queue, result);
if(n != null)
result.addChildrenNode(n);
else
return result;
}
else{
return null;
}
return result;
}
public static void main(String[] args) {
//construct tree.
Node s = new Node(1);
Node s1 = new Node(2);
Node s2 = new Node(3);
Node s3 = new Node(4);
Node s4 = new Node(5);
s1.setChildren(Arrays.asList(s4));
s.setChildren(Arrays.asList(s1,s2,s3));
StringBuffer result = traversal(new StringBuffer(),s);
Queue<String> queue = new ArrayDeque<>();
queue.addAll(Arrays.asList(result.toString().split(",")));
//Serialize it.
queue.forEach(System.out::print);
System.out.println();
Node node = new Node();
Node firstNode = new Node();
int count = 0;
//De Serialize it
while(!queue.isEmpty()){
if(count == 0){
firstNode = constructTree(queue, node);
count++;
}
else{
firstNode.addChildrenNode(constructTree(queue, node));
}
}
//Traverse the deserialized node. so that we can see the result and check whether it is true or not.
System.out.println(traversal(new StringBuffer(), firstNode));
}
}
- iniyansparkle April 23, 2016