[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' 和 输出流 ...
随机推荐
- Forms Authentication and Role based Authorization: A Quicker, Simpler, and Correct Approach
https://www.codeproject.com/Articles/36836/Forms-Authentication-and-Role-based-Authorization Problem ...
- Netty 核心组件笔记
Netty是一款高效的NIO框架和工具,基于JAVA NIO提供的API实现. 在JAVA NIO方面Selector给Reactor模式提供了基础,Netty结合Selector和Reactor模式 ...
- 正则匹配-URL-域名
DNS规定,域名中的标号都由英文字母和数字组成,每一个标号不超过63个字符,也不区分大小写字母.标号中除连字符(-)外不能使用其他的标点符号.级别最低的域名写在最左边,而级别最高的域名写在最右边.由多 ...
- 复习ing
记不住啊,我能有什么办法,只好一遍又一遍看
- 【NOIP 2018】Day2 T3 保卫王国
Problem Description Z 国有\(n\)座城市,\(n - 1\)条双向道路,每条双向道路连接两座城市,且任意两座城市 都能通过若干条道路相互到达. Z 国的国防部长小 Z 要在城市 ...
- 【NOIP 2017】Day2 T3 列队
Problem Description \(Sylvia\) 是一个热爱学习的女孩子. 前段时间,\(Sylvia\) 参加了学校的军训.众所周知,军训的时候需要站方阵. \(Sylvia\) 所在的 ...
- jquery 封装页面之间获取值
最近在项目中发页面传值比较繁琐.View → Control → View,或是Session.Cookie 的 感觉不是很好,于是封装了一个页面间的js方法,上码 $.extend({ reque ...
- Spring-MVC依赖
<dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api& ...
- Codeforces Round #200 (Div. 1) D. Water Tree 树链剖分+线段树
D. Water Tree time limit per test 4 seconds memory limit per test 256 megabytes input standard input ...
- Java生成指定长度的随机数
char[] str = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', ' ...