[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' 和 输出流 ...
随机推荐
- 终于掌握vim的寄存器和系统剪贴板的使用了- 要安装vim-X11包
vim的系统剪贴板 vim的 加号寄存器 "+ 是和系统剪贴板 相关联的. 加号寄存器和系统剪贴板之间的内容, 可以互相切换. 要把 加号寄存器中的内容, -> 放到/转移到系统剪贴板 ...
- How to check if one path is a child of another path?
How to check if one path is a child of another path? Unfortunately it's not as simple as StartsWith. ...
- 论文笔记之:Optical Flow Estimation using a Spatial Pyramid Network
Optical Flow Estimation using a Spatial Pyramid Network spynet 本文将经典的 spatial-pyramid formulation ...
- (转) K-Means聚类的Python实践
本文转自: http://python.jobbole.com/87343/ K-Means聚类的Python实践 2017/02/11 · 实践项目 · K-means, 机器学习 分享到:1 原文 ...
- Vue.set全局操作
Vue.set 的作用就是在构造器外部操作构造器内部的数据.属性或者方法.比如在vue构造器内部定义了一个count为1的数据,我们在构造器外部定义了一个方法,要每次点击按钮给值加1.就需要用到Vue ...
- 17秋 软件工程 团队第三次作业 预则立&他山之石
题目:团队作业-预则立&&他山之石 团队: 我说嘻(xì)哈(hà)你说侠 17秋 软件工程 团队第三次作业 预则立&他山之石 1.确立团队选题,建立和初步熟悉团队git的协作 ...
- 在用node安装某个全局模块的时候,没有权限修改node_modules
一.问题 今天在安装公司内部的一个npm模块的时候,发现报错了⬇ 第一行错误: deprecated graceful-fs@1.2.3: please upgrade to graceful-fs ...
- 彻底弄懂JS事件委托的概念和作用
一.写在前头 接到某厂电话问什么是事件代理的时候,一开始说addEventListener,然后他说直接绑定新的元素不会报dom不存在的错误吗?然后我就混乱了,我印象中这个方法是可以绑定新节点的 ...
- python 操作剪切板
python3 在使用网上找到的一些使用剪切板的片段时发现存在写入剪切板后乱码的情况, 研究后发现python3不能使用SetClipboardData方法, 要使用SetClipboardText ...
- PCA-主成分分析(Principal components analysis)
来自:刘建平 主成分分析(Principal components analysis,以下简称PCA)是最重要的降维方法之一. 1. PCA的思想 PCA顾名思义,就是找出数据里最主要的方面,用数据里 ...