题目:
请实现两个函数,分别用来序列化和反序列化二叉树
思路:
运用前序遍历的思路进行序列化,如果遇到null用#符号代替
代码:
/**
* Created by Hammy on 2018/2/1.
*/
public class SerializeAndDeSerialize
{
private int index = -1;
public String Serialize(TreeNode root){
StringBuffer stringBuffer = new StringBuffer();
if(root == null){
stringBuffer.append("#,");
return stringBuffer.toString();
}
stringBuffer.append(root.val + ",");
stringBuffer.append(Serialize(root.left));
stringBuffer.append(Serialize(root.right));
return stringBuffer.toString();
}
public TreeNode Deserialize(String str){
index++;
int length = str.length();
if(index >= length){
return null;
}
String[] strings = str.split(",");
TreeNode treeNode = null;
if(!strings[index].equals("#")){
treeNode = new TreeNode(Integer.valueOf(strings[index]));
treeNode.left = Deserialize(str);
treeNode.right = Deserialize(str);
}
return treeNode;
}
}
网友评论