描述

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

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

对二进制树进行反序列化或序列化的方式没有限制,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. 又是DataSnap的问题

    最近在调试DataSnap的程序,突然发现TClientDataSet打不开了,报错为dsnap200.bpl的非法地址访问,如下图: 很是怪异,干脆新建工程,只有TSQLConnection.TSQ ...

  2. Python3 tkinter基础 Listbox height 显示行数的上限

             Python : 3.7.0          OS : Ubuntu 18.04.1 LTS         IDE : PyCharm 2018.2.4       Conda ...

  3. memalign的作用【转】

    本文转载自:https://blog.csdn.net/lvwx369/article/details/41726415 转自:http://hi.baidu.com/narshben/item/ca ...

  4. tp剩余未验证内容

    new Image(宽度,高度) $(image).attr('src', ...).load(function(){....}) load表示浏览器从服务器下载(装载)对象完成, 这个load方法很 ...

  5. [转] J2EE基础知识

    Servlet总结 阐述Servlet和CGI的区别? CGI的不足之处: Servlet的优点: Servlet接口中有哪些方法及Servlet生命周期探秘 get和post请求的区别 什么情况下调 ...

  6. 图片处理工具类 util

    PathUtil package util; public class PathUtil { private static String seperator = System.getProperty( ...

  7. P4091 [HEOI2016/TJOI2016]求和

    留待警戒 FFT的时候长度要写的和函数里一样啊XD 瞎扯 这是个第二类斯特林数的理性愉悦颓柿子题目 颓柿子真的是让我hi到不行啦(才没有) 前置芝士 一个公式 \[ \sum_{i=0}^n t^i ...

  8. 在Vue的构造器里我们写一个add方法,然后我们用实例的方法调用它

    html <div id="app"> <div>{{message}}</div> </div> js var vm = new ...

  9. Java二进制指令

    转自: http://www.blogjava.net/DLevin/archive/2011/09/13/358497.html 指令从0x00-0xc9 没有0xba 常量入栈指令 指令码 操作码 ...

  10. 2、zabbix工作原理及安装配置

      Zabbix架构:zabbix基本术语.zabbix安装.配置和应用 Zabbix架构中的组件: zabbix-server:C语言    zabbix-server和zabbix-agent通过 ...