LintCode 7.Serialize and Deserialize Binary Tree(含测试代码)
题目描述
设计一个算法,并编写代码来序列化和反序列化二叉树。将树写入一个文件被称为“序列化”,读取文件后重建同样的二叉树被称为“反序列化”。
如何反序列化或序列化二叉树是没有限制的,你只需要确保可以将二叉树序列化为一个字符串,并且可以将字符串反序列化为原来的树结构。
样例
给出一个测试数据样例, 二叉树{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(含测试代码)的更多相关文章
- [LintCode] Serialize and Deserialize Binary Tree(二叉树的序列化和反序列化)
描述 设计一个算法,并编写代码来序列化和反序列化二叉树.将树写入一个文件被称为“序列化”,读取文件后重建同样的二叉树被称为“反序列化”. 如何反序列化或序列化二叉树是没有限制的,你只需要确保可以将二叉 ...
- [LeetCode] Serialize and Deserialize Binary Tree
Serialize and Deserialize Binary Tree Serialization is the process of converting a data structure or ...
- LC 297 Serialize and Deserialize Binary Tree
问题: Serialize and Deserialize Binary Tree 描述: Serialization is the process of converting a data stru ...
- 【LeetCode】297. Serialize and Deserialize Binary Tree 解题报告(Python)
[LeetCode]297. Serialize and Deserialize Binary Tree 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode ...
- 7 Serialize and Deserialize Binary Tree 序列化及反序列化二叉树
原题网址:http://www.lintcode.com/zh-cn/problem/serialize-and-deserialize-binary-tree/# 设计一个算法,并编写代码来序列化和 ...
- [LeetCode] Serialize and Deserialize Binary Tree 二叉树的序列化和去序列化
Serialization is the process of converting a data structure or object into a sequence of bits so tha ...
- LeetCode——Serialize and Deserialize Binary Tree
Description: Serialization is the process of converting a data structure or object into a sequence o ...
- Serialize and Deserialize Binary Tree
Design an algorithm and write code to serialize and deserialize a binary tree. Writing the tree to a ...
- 297. Serialize and Deserialize Binary Tree
题目: Serialization is the process of converting a data structure or object into a sequence of bits so ...
随机推荐
- js获取css的各种样式并且设置他们
js原生获取css样式,并且设置,看似简单,其实并不简单,我们平时用的ele.style.样式,只能获取内嵌的样式,但是我们写的样式基本都在style属性里面; 这里我们就需要: 下面这个代码主要是设 ...
- chosen下拉框插件的使用
效果如下 第一步: 第二步: 根据HTML5规范, 通常在引入CSS和JS时不需要指明 type,因为 text/css 和 text/javascript 分别是他们的默认值. <link r ...
- Java开发中代码规范有哪些?
Java开发中所要遵守的编码规范大体上有如下7点.命名规范.注释规范.缩进排版规范.文件名规范.声明规范.语句规范以及编程规范. 1.命名规范 (1)所有的标示符都只能用ASCⅡ字母(A-Z或a-z) ...
- Android内存泄漏排查利器LeakCanary
开源地址:https://github.com/square/leakcanary 在 build.gralde 里加上依赖, 然后sync 一下, 添加内容如下 dependencies { ... ...
- PrintDocument打印、预览、打印机设置和打印属性的方法(较完整) .
private void Form1_Load(object sender, System.EventArgs e) { //获取或设置一个值,该值指示是否发送到文件或端口 printDocument ...
- SolidWorks二次开发的研究
三维机械设计软件SolidWorks是一套基于Windows的CAD/CAE/CAM/PDM桌面集成系统,是由美国SolidWorks公司在总结和继承大型机械CAD软件的基础上,在Windows环境下 ...
- 生成centos7 安装脚本
[root@us-1-217 install]# cat gen7.py #!/usr/bin/env python # -*- coding: utf-8 -*- import os, crypt ...
- VC++动态链接库(DLL)编程
一.概论 1:http://www.pconline.com.cn/pcedu/empolder/gj/vc/0509/698632.html 2:http://pcedu.pconline.com. ...
- Jmeter入门18 Jmeter添加cookie的两种方式
jmeter中添加cookie可以通过配置HTTP Cookie Manager,也可以通过HTTP Header Manager,因为cookie是放在头文件里发送的. 实例:博客园点击添加新随笔 ...
- python入门13 集合set
set集合与数学中的集合同一个概念,是无序不重复元素组成的. #coding:utf-8 #/usr/bin/python """ 2018-11-10 dinghanh ...