- 先序递归序列化,用!来标记一个节点的结束
- 先序递归反序列化,维护一个index即可
StringBuilder builder = new StringBuilder();
int index = 0;
String Serialize(TreeNode root) {
pre(root);
return builder.toString();
}
TreeNode Deserialize(String str) {
String[] nodes = str.split("!");
return desPre(nodes);
}
private void pre(TreeNode root)
{
if(root==null)
{
builder.append("#!");
return;
}
builder.append(root.val).append("!");
pre(root.left);
pre(root.right);
}
private TreeNode desPre(String[] nodes)
{
if(index>=nodes.length)
{
return null;
}
String val = nodes[index];
if(val.equals("#"))
{
index++;
return null;
}
else{
TreeNode t = new TreeNode(Integer.parseInt(val));
index++;
t.left = desPre(nodes);
t.right = desPre(nodes);
return t;
}
}