题目:
请实现两个函数,分别用来序列化和反序列化二叉树。
分析:
序列化:我们可以按照树的前序遍历的方式,将树中的数据读出放到一个序列里。这里,对于结点是null的,也要表示出来,用以区分,这里用$作为null结点,对于非null的结点,就取出它们的值放入序列,另外,各个值之间用,隔离开,方便区分。
反序列化:根据前面序列化的序列,再结合前序遍历,可以知道第一个是根节点,再依次向后遍历,当遍历到的结点是$,表示碰到了null结点。对于此结点来说,它就不会继续递归下去了。
解法:
package com.wsy;
class Tree {
private int value;
private Tree left;
private Tree right;
public Tree() {
}
public Tree(int value) {
this.value = value;
this.left = this.right = null;
}
public Tree(int value, Tree left, Tree right) {
this.value = value;
this.left = left;
this.right = right;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public Tree getLeft() {
return left;
}
public void setLeft(Tree left) {
this.left = left;
}
public Tree getRight() {
return right;
}
public void setRight(Tree right) {
this.right = right;
}
}
public class Main {
public static int index, length;
public static String[] array = new String[0];
public static void main(String[] args) {
Tree tree = init();
String string = serialize(tree);
array = string.split(",");
index = -1;
length = array.length;
tree = deserialize();
}
public static Tree init() {
Tree tree6 = new Tree(6);
Tree tree5 = new Tree(5);
Tree tree4 = new Tree(4);
Tree tree3 = new Tree(3, tree5, tree6);
Tree tree2 = new Tree(2, tree4, null);
Tree tree1 = new Tree(1, tree2, tree3);
return tree1;
}
public static String serialize(Tree tree) {
if (tree == null) {
return "$,";
}
return tree.getValue() + "," + serialize(tree.getLeft()) + serialize(tree.getRight());
}
public static Tree deserialize() {
index++;
if (index == length || "$".equals(array[index])) {
return null;
}
Tree tree = new Tree(Integer.parseInt(array[index]));
tree.setLeft(deserialize());
tree.setRight(deserialize());
return tree;
}
}