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 ...
随机推荐
- 有关table布局时tr 属性display:block显示布局错乱
display:block display:block是可以把非块级元素强制转换为块级元素显示,如内嵌元素span,原来不支持设置宽高,宽度是由内容撑开的; display:table-row tab ...
- SharePoint 2013 - Client OM
1. 向 executeQueryAsync 中传递参数可以使用以下两种方式,也可以参考这篇文章: var mySuccessCallBack = Function.createCallback(on ...
- select * from pet where species regexp '^c';
select * from pet where species regexp '^c';
- js 时间特效
http://example.com:1234/test.htm#part2:Hash的作用. http://www.cnblogs.com/Interkey/p/RunAsAdmin.html
- mysql忘记root用户密码重置密码的方式
解决方法如下: 让mysql不载入权限表,命令:mysqld --skip-grant-tables(windows).mysqld_safe --skip-grant-tables user=mys ...
- SQL Server ->> 生成时间类型的Partition Function和Partition Scheme代码
有时工作中要建个分区函数,可是像日期这种分区函数要是搞个几百个的值那不是要搞死我.于是写了点代码自动生成一个从1990年开始的按月的分区函数和对应的分区主题 USE [TestDB] GO DECLA ...
- POSIX 线程详解(经典必看)
http://www.cnblogs.com/sunminmin/p/4479952.html 总共三部分: 第一部分:POSIX 线程详解 ...
- QT隐含共享类 QSharedData QSharedDataPointer
版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/davidsu33/article/details/28857391 QT中非常多类都实现了隐含共享比 ...
- HDU 5536 Chip Factory 【01字典树删除】
题目传送门:http://acm.hdu.edu.cn/showproblem.php?pid=5536 Chip Factory Time Limit: 18000/9000 MS (Java/Ot ...
- listBox获取项的方法
获取所有项 ; i < LB.Items.Count;i++ )2 {3 str_arr.Add(LB.Items[i].ToString()); 4 } 获取指定项 string str=LB ...