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 ...
随机推荐
- Topcoder SRM 698 Div1 250 RepeatString(dp)
题意 [题目链接]这怎么发链接啊..... Sol 枚举一个断点,然后类似于LIS一样dp一波 这个边界条件有点迷啊..fst了两遍... #include<bits/stdc++.h> ...
- Web站点如何防范XSS、CSRF、SQL注入攻击
XSS跨站脚本攻击 XSS跨站脚本攻击指攻击者在网页中嵌入客户端脚本(例如JavaScript),当用户浏览此网页时,脚本就会在用户的浏览器上执行,从而达到攻击者的目的,比如获取用户的Cookie,导 ...
- 转载《学习HTML5 canvas遇到的问题》
学习HTML5 canvas遇到的问题 1. 非零环绕原则(nonzZero rule) 非零环绕原则是canvas在进行填充的时候是否要进行填充的判断依据. 在判断填充的区域拉一条线出来,拉到图形的 ...
- toMapFromStage layerDefinitions ClassBreakRenderer
class Map 方法 toMapFromStage 用于把屏幕坐标转换为地理坐标 public function toMapFromStage(stageX:Number, stageY:Numb ...
- 【Linux】Linux远程登陆
登录任务 Windows主机--远程登录--Linux主机 一.登陆前提准备 1.1 确保网络通畅 确保从Windows 能够Ping通Linux 1.2 关闭Linux防火墙 //前提:以root管 ...
- Socket.Receive 无法预知字节长度的数据接收
话不多说直接上代码: string recvStr = ""; byte[] recvBytes = new byte[1024]; int bytes; do { bytes = ...
- 插上翅膀,让Excel飞起来——xlwings(三)
xlwings基本对象 xlwings基本对象 App相当于Excel程序,Book相当于工作簿.N个Excel程序则由apps表示,N个工作簿由books表示. 对工作簿的操作 #导入xlwings ...
- QQ空间那年今日 & 人人过往的今天
都说天下文章一大抄!就看你会抄不会抄! 过往的今天这个功能很新颖,不过最后还是被企鹅抄走了~该出手时就出手! 自从过往的今天功能低调上线后,断断续续总是有人提到这个功能,有褒有贬: 顶的认为人人让自己 ...
- Git warning push.default is unset
warning: push.default is unset; its implicit value is changing in Git 2.0 from 'matching' to 'simple ...
- hdu1852 Beijing 2008
题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=1852 题目大意: 求2008^n的所有因子和m对k取余,然后求2008^m对k取余. 解题思路: 首 ...