[LintCode] Serialize and Deserialize Binary Tree(二叉树的序列化和反序列化)
描述
设计一个算法,并编写代码来序列化和反序列化二叉树。将树写入一个文件被称为“序列化”,读取文件后重建同样的二叉树被称为“反序列化”。
如何反序列化或序列化二叉树是没有限制的,你只需要确保可以将二叉树序列化为一个字符串,并且可以将字符串反序列化为原来的树结构。
对二进制树进行反序列化或序列化的方式没有限制,LintCode将您的serialize输出作为deserialize的输入,它不会检查序列化的结果。
样例
给出一个测试数据样例, 二叉树{3,9,20,#,#,15,7},表示如下的树结构:
3
/ \
9 20
/ \
15 7
我们的数据是进行 BFS 遍历得到的。当你测试结果 wrong answer时,你可以作为输入调试你的代码。
你可以采用其他的方法进行序列化和反序列化。
代码
GitHub 的源代码,请访问下面的链接:
package com.ossez.lang.tutorial.tests.lintcode; import java.util.ArrayList; import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import com.ossez.lang.tutorial.models.TreeNode; /**
* <p>
* 7
* <ul>
* <li>@see <a href=
* "https://www.cwiki.us/display/ITCLASSIFICATION/Serialize+and+Deserialize+Binary+Tree">https://www.cwiki.us/display/ITCLASSIFICATION/Serialize+and+Deserialize+Binary+Tree</a>
* <li>@see<a href=
* "https://www.lintcode.com/problem/serialize-and-deserialize-binary-tree">https://www.lintcode.com/problem/serialize-and-deserialize-binary-tree</a>
* </ul>
* </p>
*
* @author YuCheng
*
*/
public class LintCode0007SerializeAndDeserialize { private final static Logger logger = LoggerFactory.getLogger(LintCode0007SerializeAndDeserialize.class); /**
*
*/
@Test
public void testMain() {
logger.debug("BEGIN");
String data = "{3,9,20,#,#,15,7}"; System.out.println(serialize(deserialize(data))); } /**
* Deserialize from array to tree
*
* @param data
* @return
*/
private TreeNode deserialize(String data) {
// NULL CHECK
if (data.equals("{}")) {
return null;
} ArrayList<TreeNode> treeList = new ArrayList<TreeNode>(); data = data.replace("{", "");
data = data.replace("}", "");
String[] vals = data.split(","); // INSERT ROOT
TreeNode root = new TreeNode(Integer.parseInt(vals[0]));
treeList.add(root); int index = 0;
boolean isLeftChild = true;
for (int i = 1; i < vals.length; i++) {
if (!vals[i].equals("#")) {
TreeNode node = new TreeNode(Integer.parseInt(vals[i]));
if (isLeftChild) {
treeList.get(index).left = node;
} else {
treeList.get(index).right = node;
}
treeList.add(node);
} // LEVEL
if (!isLeftChild) {
index++;
} // MOVE TO RIGHT OR NEXT LEVEL
isLeftChild = !isLeftChild;
} return root; } /**
*
* @param root
* @return
*/
public String serialize(TreeNode root) {
// write your code here
if (root == null) {
return "{}";
} ArrayList<TreeNode> queue = new ArrayList<TreeNode>();
queue.add(root); for (int i = 0; i < queue.size(); i++) {
TreeNode node = queue.get(i);
if (node == null) {
continue;
}
queue.add(node.left);
queue.add(node.right);
} while (queue.get(queue.size() - 1) == null) {
queue.remove(queue.size() - 1);
} StringBuilder sb = new StringBuilder();
sb.append("{");
sb.append(queue.get(0).val);
for (int i = 1; i < queue.size(); i++) {
if (queue.get(i) == null) {
sb.append(",#");
} else {
sb.append(",");
sb.append(queue.get(i).val);
}
}
sb.append("}");
return sb.toString();
} }
点评
本题目主要需要你对二叉树的遍历方法有所了解。
遍历二叉树主要有 2 类方法,分别为深度优先(DFS)和广度优先(BFS)。
在深度优先中,你有又可以使用前序,中序和后序搜索方法,你可以使用递归或者非递归算法实现。对于广度优先算法,一般都会采用非递归的实现方法进行实现。
[LintCode] Serialize and Deserialize Binary Tree(二叉树的序列化和反序列化)的更多相关文章
- 297 Serialize and Deserialize Binary Tree 二叉树的序列化与反序列化
序列化是将一个数据结构或者对象转换为连续的比特位的操作,进而可以将转换后的数据存储在一个文件或者内存中,同时也可以通过网络传输到另一个计算机环境,采取相反方式重构得到原数据.请设计一个算法来实现二叉树 ...
- [LeetCode] 297. Serialize and Deserialize Binary Tree 二叉树的序列化和反序列化
Serialization is the process of converting a data structure or object into a sequence of bits so tha ...
- 297. Serialize and Deserialize Binary Tree二叉树的序列化和反序列化(就用Q)
[抄题]: Serialization is the process of converting a data structure or object into a sequence of bits ...
- [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】297. Serialize and Deserialize Binary Tree 解题报告(Python)
[LeetCode]297. Serialize and Deserialize Binary Tree 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode ...
- [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 ...
- [Java]LeetCode297. 二叉树的序列化与反序列化 | Serialize and Deserialize Binary Tree
Serialization is the process of converting a data structure or object into a sequence of bits so tha ...
- 【LeetCode】297. Serialize and Deserialize Binary Tree
二叉树的序列化与反序列化. 如果使用string作为媒介来存储,传递序列化结果的话,会给反序列话带来很多不方便. 这里学会了使用 sstream 中的 输入流'istringstream' 和 输出流 ...
随机推荐
- 01 Hello World!
from tkinter import Label#获取组件对象 widget=Label(None,text='Hello GUI world!')#生成 widget.pack()#布置 widg ...
- CSS的再深入3(更新中···)
在前面,我们学习了标准文档流,但在实际制作的过程中,用标准文档流书写显然是不现实的,因此,我们来了解几种脱离标准文档流的方法: 1.float 浮动 float:left/right:(左浮/右浮) ...
- RPMB分区介绍【转】
本文转载自:https://blog.csdn.net/xiezhi123456/article/details/81479793 RPMB(Replay Protected Memory Block ...
- Flutter第1天--初始分析+Dart方言+Canvas简绘 - 云+社区
Flutter第1天--初始分析+Dart方言+Canvas简绘 - 云+社区 - 腾讯云 https://cloud.tencent.com/developer/article/1378974
- 2018年第九届蓝桥杯B组题C++汇总解析-fishers
2018年第九届蓝桥杯B组题C++解析-fishers 题型 第一题:第几天 第二题:明码 第三题:乘积尾零 第四题:测试次数 第五题:快速排序 第六题:递增三元组 第七题:螺旋折线 第八题:日志统计 ...
- A^B mod C (快速幂+快速乘+取模)题解
A^B mod C Given A,B,C, You should quickly calculate the result of A^B mod C. (1<=A,B,C<2^63). ...
- 一个涉及到浮点寄存器的CM
这次找小伙伴要了他的一个CM,怎么说呢,这CM让我学到了不少,其实搞出来后感觉不难,就是有不少FPU浮点相关的指令和FPU寄存器完全没学过,查了不少资料,学到了很多 打开是这样 无壳程序,我们直接od ...
- java 安装环境
网上关于win10 jdk安装.配置环境变量的经验有很多,但是按照方法配置后出现了运行javac 报告javac不是内部或外部命令,但是运行java.java-version正常.并不是说那些经验不正 ...
- 论文笔记之:Heterogeneous Face Attribute Estimation: A Deep Multi-Task Learning Approach
Heterogeneous Face Attribute Estimation: A Deep Multi-Task Learning Approach 2017.11.28 Introductio ...
- (转)PaperWeekly 第二十二期---Image Caption任务综述
本文转自:http://mp.weixin.qq.com/s?__biz=MzIwMTc4ODE0Mw==&mid=2247484014&idx=1&sn=4a053986f5 ...