描述

设计一个算法,并编写代码来序列化和反序列化二叉树。将树写入一个文件被称为“序列化”,读取文件后重建同样的二叉树被称为“反序列化”。

如何反序列化或序列化二叉树是没有限制的,你只需要确保可以将二叉树序列化为一个字符串,并且可以将字符串反序列化为原来的树结构。

对二进制树进行反序列化或序列化的方式没有限制,LintCode将您的serialize输出作为deserialize的输入,它不会检查序列化的结果。

样例

给出一个测试数据样例, 二叉树{3,9,20,#,#,15,7},表示如下的树结构:

  3
/ \
9 20
/ \
15 7

我们的数据是进行 BFS 遍历得到的。当你测试结果 wrong answer时,你可以作为输入调试你的代码。

你可以采用其他的方法进行序列化和反序列化。

代码

GitHub 的源代码,请访问下面的链接:

https://github.com/cwiki-us/java-tutorial/blob/master/src/test/java/com/ossez/lang/tutorial/tests/lintcode/LintCode0007SerializeAndDeserialize.java

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(二叉树的序列化和反序列化)的更多相关文章

  1. 297 Serialize and Deserialize Binary Tree 二叉树的序列化与反序列化

    序列化是将一个数据结构或者对象转换为连续的比特位的操作,进而可以将转换后的数据存储在一个文件或者内存中,同时也可以通过网络传输到另一个计算机环境,采取相反方式重构得到原数据.请设计一个算法来实现二叉树 ...

  2. [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 ...

  3. 297. Serialize and Deserialize Binary Tree二叉树的序列化和反序列化(就用Q)

    [抄题]: Serialization is the process of converting a data structure or object into a sequence of bits ...

  4. [LeetCode] Serialize and Deserialize Binary Tree 二叉树的序列化和去序列化

    Serialization is the process of converting a data structure or object into a sequence of bits so tha ...

  5. 【LeetCode】297. Serialize and Deserialize Binary Tree 解题报告(Python)

    [LeetCode]297. Serialize and Deserialize Binary Tree 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode ...

  6. [LeetCode] Serialize and Deserialize Binary Tree

    Serialize and Deserialize Binary Tree Serialization is the process of converting a data structure or ...

  7. LC 297 Serialize and Deserialize Binary Tree

    问题: Serialize and Deserialize Binary Tree 描述: Serialization is the process of converting a data stru ...

  8. [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 ...

  9. 【LeetCode】297. Serialize and Deserialize Binary Tree

    二叉树的序列化与反序列化. 如果使用string作为媒介来存储,传递序列化结果的话,会给反序列话带来很多不方便. 这里学会了使用 sstream 中的 输入流'istringstream' 和 输出流 ...

随机推荐

  1. Docker中的Cgroup Driver:Cgroupfs 与 Systemd

    在安装kubernetes的过程中,会出现 failed to create kubelet: misconfiguration: kubelet cgroup driver: "cgrou ...

  2. bootstrap图片上传功能

    重点: fileupload    .loadImage 引用js: <!-- Bootstrap CSS --> <link href="~/lib/bootstrap/ ...

  3. Java String 函数常用操作 & format() 格式化输出,代码详解

    package _String_; import java.util.*; import java.math.*; import java.lang.*; public class _Strings ...

  4. PTA 7-2 符号配对(20 分)

    7-2 符号配对(20 分) 请编写程序检查C语言源程序中下列符号是否配对:/*与*/.(与).[与].{与}. 输入格式: 输入为一个C语言源程序.当读到某一行中只有一个句点.和一个回车的时候,标志 ...

  5. 2、iptables基本应用

    iptables:规则管理工具 添加.修改.删除.显示等: 规则和链有计数器: pkts:  由规则或链所匹配到的报文的个数: bytes:由规则或链匹配到的所有报文大小之和: iptables命令: ...

  6. 用maven和spring搭建ActiveMQ环境

    前面搭建过了简单的环境,这次用稍微实际一点的maven+spring+activemq来进行搭建 准备:win7,eclipse,jdk1.8,tomcat8,maven3.5.2,activemq5 ...

  7. repr() 和 str() 函数

    这两个函数都是可以用来将值转换成字符串的. 函数str() 用于将值转化为适于人阅读的形式,而repr() 转化为供解释器读取的形式. 结果是:

  8. 【Cucumber】【命令行】

    知识点 参考:https://www.cnblogs.com/worklog/p/5253297.html cucumber的命令行选项 首先查看命令行选项.和其它命令行工具一样,cucumber提供 ...

  9. 【Django】【问题集锦】

    参考:http://www.linuxidc.com/Linux/2013-03/80649.htm 1. Django的shell模式下,如果报warning,则再执行一次,也许就好了 2. Dja ...

  10. 基于 Python 和 Pandas 的数据分析(6) --- Joining and Merging

    这一节我们将看一下如何通过 join 和 merge 来合并 dataframe. import pandas as pd df1 = pd.DataFrame({'HPI':[80,85,88,85 ...