public class Codec {
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
if(root==null) return "";
Queue<TreeNode> queue=new LinkedList<>();
StringBuilder res=new StringBuilder();
queue.offer(root);
while(!queue.isEmpty()){
TreeNode cur=queue.poll();
if(cur==null){
res.append("n ");
continue;
}
res.append(cur.val+" ");
queue.offer(cur.left);
queue.offer(cur.right);
}
return res.toString();
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if(data=="") return null;
Queue<TreeNode> queue=new LinkedList<>();
String[] values=data.split(" ");
TreeNode root=new TreeNode(Integer.parseInt(values[0]));
queue.offer(root);
for(int i=1;i<values.length;i++){
TreeNode cur=queue.poll();
if(!values[i].equals("n")){
TreeNode left=new TreeNode(Integer.parseInt(values[i]));
cur.left=left;
queue.offer(left);
}
if (!values[++i].equals("n")) {
TreeNode right = new TreeNode(Integer.parseInt(values[i]));
cur.right = right;
queue.add(right);
}
}
return root;
}
}
297. Serialize and Deserialize Binary Tree
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- Serialization is the process of converting a data structu...
- 二叉树的序列化和反序列化。我一开始想用BFS的,但第一不知道怎么处理空子树,第二不知道怎么还原一棵树。于是照着so...
- 原题 设计一个算法,并编写代码来序列化和反序列化二叉树。将树写入一个文件被称为“序列化”,读取文件后重建同样的二叉...
- 题目297. Serialize and Deserialize Binary Tree Serializatio...
- 106. Construct Binary Tree from Inorder and Postorder Tra...