设计一个算法,并编写代码来序列化和反序列化二叉树。将树写入一个文件被称为“序列化”,读取文件后重建同样的二叉树被称为“反序列化”。
如何反序列化或序列化二叉树是没有限制的,你只需要确保可以将二叉树序列化为一个字符串,并且可以将字符串反序列化为原来的树结构。
注意事项
There is no limit of how you deserialize or serialize a binary tree, LintCode will take your output of serialize as the input of deserialize, it won't check the result of serialize.
您在真实的面试中是否遇到过这个题? Yes
样例
给出一个测试数据样例, 二叉树{3,9,20,#,#,15,7},表示如下的树结构:
3
/ \
9 20
/ \
15 7
我们的数据是进行BFS遍历得到的。当你测试结果wrong answer时,你可以作为输入调试你的代码。
如何反序列化或序列化二叉树是没有限制的,你只需要确保可以将二叉树序列化为一个字符串,并且可以将字符串反序列化为原来的树结构。
注意事项
There is no limit of how you deserialize or serialize a binary tree, LintCode will take your output of serialize as the input of deserialize, it won't check the result of serialize.
您在真实的面试中是否遇到过这个题? Yes
样例
给出一个测试数据样例, 二叉树{3,9,20,#,#,15,7},表示如下的树结构:
3
/ \
9 20
/ \
15 7
我们的数据是进行BFS遍历得到的。当你测试结果wrong answer时,你可以作为输入调试你的代码。
你可以采用其他的方法进行序列化和反序列化。
import java.util.Scanner;
import java.util.Stack;
/**
* 设计一个算法,并编写代码来序列化和反序列化二叉树。将树写入一个文件被称为“序列化”,读取文件后重建同样的二叉树被称为“反序列化”。
如何反序列化或序列化二叉树是没有限制的,你只需要确保可以将二叉树序列化为一个字符串,并且可以将字符串反序列化为原来的树结构。
注意事项
There is no limit of how you deserialize or serialize a binary tree, LintCode will take your output of serialize as the input of deserialize, it won't check the result of serialize.
您在真实的面试中是否遇到过这个题? Yes
样例
给出一个测试数据样例, 二叉树{3,9,20,#,#,15,7},表示如下的树结构:
3
/ \
9 20
/ \
15 7
我们的数据是进行BFS遍历得到的。当你测试结果wrong answer时,你可以作为输入调试你的代码。
你可以采用其他的方法进行序列化和反序列化。
*
* @author Dell
*
*/
public class Test7 {
public static String serialize(TreeNode root)
{
if(root==null) //不要忘记写
return "";
StringBuilder sb=new StringBuilder();
Stack<TreeNode> s=new Stack<>();
TreeNode p=root;
while(p!=null||s.isEmpty()!=true)
{
if(p!=null)
{
sb.append(p.val+" ");
s.push(p);
p=p.left;
}
else
{
sb.append("# ");
TreeNode temp=s.pop();
p=temp.right;
if(p==null&&s.isEmpty()==true)
sb.append("# ");
}
}
return sb.toString().trim();
}
public static TreeNode deseriablize(String data)
{ if(data=="") //不要忘记写
return null;
Scanner sc=new Scanner(data);
TreeNode t=null;
return CreatTree(t,sc);
}
private static TreeNode CreatTree(TreeNode t, Scanner sc) {
String temp=sc.next();
if(temp.trim().equals("#"))
return null;
else
{
t=new TreeNode(Integer.parseInt(temp));
t.left=CreatTree(t.left,sc);
t.right=CreatTree(t.right,sc);
return t;
}
}
public static void preorder(TreeNode t)
{
if(t!=null)
{
System.out.print(t.val+" ");
preorder(t.left);
preorder(t.right);
}
}
public static void main(String[] args) {
TreeNode t=new TreeNode(1);
t.left=new TreeNode(2);
t.right=new TreeNode(4);
t.left.left=new TreeNode(3);
t.right.left=new TreeNode(5);
t.right.right=new TreeNode(7);
t.right.left.right=new TreeNode(6);
System.out.println(serialize(t));
TreeNode tree=deseriablize(serialize(t));
preorder(tree);
}
}