题目描述

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

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

样例

给出一个测试数据样例, 二叉树{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. redux基本使用

    redux数据流向 基本使用

  2. openssl命令使用

    openssl openssl是个密码工具集,提供多端接口调用方式 组成: 1. 代码库 libcryto ,libssl(ssl/tls) 2. 工具集 openssl 对称加密 对称加密主要是用a ...

  3. mysql四-2:多表查询

    一.介绍 本节主题: 多表连接查询 复合条件连接查询 子查询 准备表: #建表 create table department( id int, name ) ); create table empl ...

  4. PHP Primary script unknown 终极解决方法

    相信很多配置php环境的都遇到过这个恼人的问题: 浏览器访问php文件,返回来 File not found 查看/var/log/nginx/error.log ,有 “Primary script ...

  5. 开发Windows RT平台下的Windows应用商店应用程序的遇到的问题备忘

    1. 关于获取Win8开发者许可证的问题: 有一种情况是:如果系统是Win8.0, 那么如果先激活了windows8(用激活工具), 再安装VS2012,那么在新建项目时会提示获取windows8开发 ...

  6. 【Spring实战】—— 2 构造注入

    本文讲解了构造注入以及spring的基本使用方式,通过一个杂技演员的例子,讲述了依赖注入属性或者对象的使用方法. 如果想要使用spring来实现依赖注入,需要几个重要的步骤: 1 定义主要的类和需要分 ...

  7. 关于Oracle死锁处理方法

    关于数据库死锁的检查方法一.         数据库死锁的现象程序在执行的过程中,点击确定或保存按钮,程序没有响应,也没有出现报错.二.         死锁的原理当对于数据库某个表的某一列做更新或删 ...

  8. 建立virtualenv环境

    建立virtualenv环境 virtualenv --no-site-packages yourenv 其中,yourenv是给环境起的名称 --no-site-packages表示安装的pytho ...

  9. ZT c++ 中的重载全局new,delete

    c++ 中的重载全局new,delete 分类: c++ 2010-08-06 10:31 116人阅读 评论(1) 收藏 举报 deletec++file编译器语言工作 最近做一个小项目,对c++又 ...

  10. Jupyter notebook远程访问linux服务器

    [转]https://blog.csdn.net/akon_wang_hkbu/article/details/78973366