将内存中一棵树变成字符串的形式,然后再将这一段字符串变成一棵树。
可以说就是讲遍历一遍后的结果用一个字符串保存下来。
可以使用先序遍历、中序遍历、后序遍历、层序遍历都行。
//序列化一个二叉树
public static String NodeToString(NodeTwo head) {
if(head == null) {
return "#_";
}
String s = head.value+"_";
s += NodeToString(head.left);
s += NodeToString(head.right);
return s;
}
//将链表拆分成一个String类型数组,然后再存到队列里面。
public static NodeTwo reconByPreString(String s) {
String[] sp = s.split("_");
Queue queue = new linkedList();
for(String string:sp) {
queue.add(string);
}
return reconPreOrder(queue);
}
//从队列中取出节点,建立二叉树
public static NodeTwo reconPreOrder(Queue queue) {
String s = queue.poll();
if(s.equals("#")) {
return null;
}
//因为是先序遍历的序列化,所以是按照中左右的顺序来的。
NodeTwo head = new NodeTwo(Integer.valueOf(s));
head.left = reconPreOrder(queue);
head.right = reconPreOrder(queue);
return head;
}



