题目:请实现一个函数,分别用来序列化和反序列化二叉树
思路:序列化的时候,用中序遍历,注意叶子节点的左右子节点用“#”代替;反序列化的时候,也是按照中序遍历的顺序。
解决方案:
public class Question37 {
static class BinaryTreeNode {
int value;
BinaryTreeNode left;
BinaryTreeNode right;
public BinaryTreeNode(int value) {
this.value = value;
}
}
public static String serialize(BinaryTreeNode root){
StringBuffer sb = new StringBuffer();
if (root == null){
sb.append("#,");
return sb.toString();
}
sb.append(root.value + ",");
sb.append(serialize(root.left));
sb.append(serialize(root.right));
return sb.toString();
}
static int index = -1;
public static BinaryTreeNode deSerialize(String str){
index++;
int len = str.length();
if (index >= len) return null;
String[] strArray = str.split(",");
BinaryTreeNode node = null;
if (!strArray[index].equals("#")){
node = new BinaryTreeNode(Integer.valueOf(strArray[index]));
node.left = deSerialize(str);
node.right = deSerialize(str);
}
return node;
}
public static void main(String[] args) {
BinaryTreeNode pHead = new BinaryTreeNode(3);
BinaryTreeNode pAhead = new BinaryTreeNode(2);
BinaryTreeNode pBhead = new BinaryTreeNode(5);
BinaryTreeNode pChead = new BinaryTreeNode(7);
BinaryTreeNode pDhead = new BinaryTreeNode(1);
pHead.left = pAhead;
pHead.right = pBhead;
pBhead.left = pChead;
pAhead.left = pDhead;
System.out.println(serialize(pHead));
}
}
网友评论