题目描述

设计一个算法,并编写代码来序列化和反序列化二叉树。将树写入一个文件被称为“序列化”,读取文件后重建同样的二叉树被称为“反序列化”。

如何反序列化或序列化二叉树是没有限制的,你只需要确保可以将二叉树序列化为一个字符串,并且可以将字符串反序列化为原来的树结构。

样例

给出一个测试数据样例, 二叉树{3,9,20,#,#,15,7},表示如下的树结构:

我们的数据是进行BFS遍历得到的。当你测试结果wrong answer时,你可以作为输入调试你的代码。你可以采用其他的方法进行序列化和反序列化。


在编程过程中,采用Queue队列结构来保存树节点,因此有必要熟悉一下Queue接口(Deque接口是Queue接口的子接口,代表一个双端队列)的相关知识点。

1.Queue接口与List、Set属于同一级别,都是继承了Collection接口。LinkedList类实现了Queue接口,因此我们可以把LinkedList当成Queue来用。

2.Queue使用时要尽量避免Collection的add()和remove()方法,而是要使用offer()来加入元素,使用poll()来获取并移出元素。它们的优点是通过返回值可以判断成功与否,而add()和remove()方法在失败的时候会抛出异常。

另外要用到字符串结构,需弄明白 String, StringBuilder 以及 StringBuffer 这三个类之间有什么区别?

1.首先说运行速度,或者说是执行速度,在这方面运行速度快慢为:StringBuilder > StringBuffer > String

  String最慢的原因:

  String为字符串常量,而StringBuilder和StringBuffer均为字符串变量,即String对象一旦创建之后该对象是不可更改的,但后两者的对象是变量,是可以更改的。

2. 再来说线程安全

  在线程安全上,StringBuilder是线程不安全的,而StringBuffer是线程安全的。

因此:
  String:适用于少量的字符串操作的情况

  StringBuilder:适用于单线程下在字符缓冲区进行大量操作的情况

  StringBuffer:适用多线程下在字符缓冲区进行大量操作的情况

实现代码:

 import java.util.LinkedList;
import java.util.Queue; class TreeNode {
public int val;//节点的值
public TreeNode left,right;//左右节点
public TreeNode(int val){
this.val = val;//初始化节点
this.left = this.right = null;
}
} public class SerializeTree {
public static void main(String[] args) throws Exception {
TreeNode node1 = new TreeNode(3);
TreeNode node2 = new TreeNode(9);
TreeNode node3 = new TreeNode(20);
node1.left = node2;
node1.right = node3;
TreeNode node4 = new TreeNode(15);
TreeNode node5 = new TreeNode(7);
node3.left = node4;
node3.right = node5; String s = new SerializeTree().serialize(node1);
System.out.println(s); String str = new String("3,9,20,#,#,15,7");
//TreeNode root = new SerializeTree().deserialize(s);
TreeNode root = new SerializeTree().deserialize(str);
System.out.println((int)root.val);
System.out.println(root.left.val);
System.out.println(root.right.val); } /*将一棵树序列化一个字符串*/
public String serialize(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
StringBuffer sb = new StringBuffer(); queue.offer(root);
while(!queue.isEmpty()) {
TreeNode data = queue.poll();
if(data != null) {
sb.append(data.val+",");
queue.offer(data.left);
queue.offer(data.right);
}
else
sb.append("#,");
}
//return sb.toString();
return sb.substring(0, sb.length()-1);//去掉字符串末尾的“,”号
} /*将一个字符串反序列化为一棵树*/
public TreeNode deserialize(String data) throws Exception {
Queue<TreeNode> queue = new LinkedList<>();
String string = data.substring(0, data.length());
String[] s = string.split(",");
/*for(int i =0;i<s.length-1;i++) {
System.out.print(s[i]+" ");
}
System.out.println(s[s.length-1]);*/
int i = 0;
if(s[i].equals("#"))
return null; TreeNode root = new TreeNode(Integer.parseInt(s[i]));
queue.offer(root); while(!queue.isEmpty() && i < s.length-1 ) {
i++;
TreeNode tmp = queue.poll(); if(s[i].equals("#")) { tmp.left = null;
}
else
{
TreeNode left = new TreeNode(Integer.parseInt(s[i]));
tmp.left = left;
queue.offer(left);
} i++;
if(s[i].equals("#"))
tmp.right = null;
else
{
TreeNode right = new TreeNode(Integer.parseInt(s[i]));
tmp.right = right;
queue.offer(right);
}
}
return root;
} }

LintCode 7.Serialize and Deserialize Binary Tree(含测试代码)的更多相关文章

  1. [LintCode] Serialize and Deserialize Binary Tree(二叉树的序列化和反序列化)

    描述 设计一个算法,并编写代码来序列化和反序列化二叉树.将树写入一个文件被称为“序列化”,读取文件后重建同样的二叉树被称为“反序列化”. 如何反序列化或序列化二叉树是没有限制的,你只需要确保可以将二叉 ...

  2. [LeetCode] Serialize and Deserialize Binary Tree

    Serialize and Deserialize Binary Tree Serialization is the process of converting a data structure or ...

  3. LC 297 Serialize and Deserialize Binary Tree

    问题: Serialize and Deserialize Binary Tree 描述: Serialization is the process of converting a data stru ...

  4. 【LeetCode】297. Serialize and Deserialize Binary Tree 解题报告(Python)

    [LeetCode]297. Serialize and Deserialize Binary Tree 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode ...

  5. 7 Serialize and Deserialize Binary Tree 序列化及反序列化二叉树

    原题网址:http://www.lintcode.com/zh-cn/problem/serialize-and-deserialize-binary-tree/# 设计一个算法,并编写代码来序列化和 ...

  6. [LeetCode] Serialize and Deserialize Binary Tree 二叉树的序列化和去序列化

    Serialization is the process of converting a data structure or object into a sequence of bits so tha ...

  7. LeetCode——Serialize and Deserialize Binary Tree

    Description: Serialization is the process of converting a data structure or object into a sequence o ...

  8. Serialize and Deserialize Binary Tree

    Design an algorithm and write code to serialize and deserialize a binary tree. Writing the tree to a ...

  9. 297. Serialize and Deserialize Binary Tree

    题目: Serialization is the process of converting a data structure or object into a sequence of bits so ...

随机推荐

  1. [JAVA小项目]GUI界面的局域网聊天室

    思路: 1.服务端: 1.1 创建ServerSocket 监听本地端口 1.2 循环接收多个客户端的连接,并且把多个客户端连接的每个管道都为其创建线程. 服务端类的成员:链表--每个成员都是线程类- ...

  2. 常用DOM结构方法总结

    ---内容开始--- 获取元素的方法: getElementById() 通过ID名获取元素 getElementsByTagName() 通过元素(标签)名称 getElementsByClassN ...

  3. 转 【<meta name="description" content=">】作用讲解

    今天在看别人写的网站代码,发现类似<meta name="Keywords" content="" >.<meta name="De ...

  4. http状态码汇总及代表意思

    成功2×× 成功处理了请求的状态码.200 服务器已成功处理了请求并提供了请求的网页.204 服务器成功处理了请求,但没有返回任何内容. 重定向3×× 每次请求中使用重定向不要超过 5 次.301 请 ...

  5. AE多用户同时编辑同一个版本数据的解决方法

    项目中做了入库的功能,测试一切正常,但是实际使用多个用户同时编辑default版本的时候,问题就来了,StopEditing 错误信息如下 FDO_E_VERSION_REDEFINED -21472 ...

  6. php *-devel

    源码编译安装个php,缺少好多-devel的库. why devel? devel包至少包括头文件和链接库.如果你的要安装的源码依赖某个库,那肯定需要这两样东西. 让apache支持php 在编译ph ...

  7. C#多线程和异步(二)——Task和async/await详解(转载)

    一.什么是异步 同步和异步主要用于修饰方法.当一个方法被调用时,调用者需要等待该方法执行完毕并返回才能继续执行,我们称这个方法是同步方法:当一个方法被调用时立即返回,并获取一个线程执行该方法内部的业务 ...

  8. Daemon 自更新

    NSTask *task = [[NSTask alloc] init]; [task setLaunchPath:@"usr/bin/dpkg"]; [task setArgum ...

  9. wxpython 对话框

    . 消息对话框(wx.MessageDialog) 消息对话框 与用户通信最基本的机制是wx.MessageDialog,它是一个简单的提示框. wx.MessageDialog可用作一个简单的OK框 ...

  10. network embedding 需读论文

    Must-read papers on NRL/NE. github: https://github.com/nate-russell/Network-Embedding-Resources NRL: ...