Problem Link
序列化和反序列化一棵二叉树。序列化的定义是,能把树结构转化成string。但序列化就是能根据string转化成二叉树。举个栗子:
1
/ \
2 3
/ \
4 5
最简单的姿势,就是把它当成满二叉树处理,对于空节点就用特殊字符代替(用null代替有四个字符呢),比方说我们用
,则上面这棵树的序列化结果就是[1,2,3,
, $,4,5]。
先序遍历
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Codec {
int index = -1;
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
StringBuffer strbuf = new StringBuffer();
if(root == null){
strbuf.append("$,");
return strbuf.toString();
}
strbuf.append(root.val + ",");
strbuf.append(serialize(root.left));
strbuf.append(serialize(root.right));
return strbuf.toString();
}
public TreeNode Deserialize(String[] str) {
index++;
int len = str.length;
if (index > len) return null;
TreeNode node = null;
if(!str[index].equals("$")){
node = new TreeNode(Integer.valueOf(str[index]));
node.left = Deserialize(str);
node.right = Deserialize(str);
}
return node;
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
String[] str = data.split(",");
index = -1;
return Deserialize(str);
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));
这种方法的缺点很明显,就是当树中空结点数量多的时候,序列中会有大量的$,浪费。
前序遍历+中序遍历
唔。。就想想优化,不想写代码。懒。。这个要遍历两次,但序列的长度在树比较稀疏的时候,会缩短
相类似的想法是,在遍历的时候,标记一下当前这个结点是左子树还是右子树