Description:

Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.

Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.

For example, you may serialize the following tree

    1
/ \
2 3
/ \
4 5 as "[1,2,3,null,null,4,5]", just the same as how LeetCode OJ serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.

Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.

本以为二叉树已经刷的比较溜了,但是还是踩了各种坑。。。

题目大意是按照对应的规则序列化和反序列化二叉树。其实就是求二叉树"按层"遍历序列和根据按层遍历序列求二叉树。但是这里的按层遍历是局部对称的,如果一个节点不为null,则就必须存储它的左右子节点,如果子节点为null就存成"null"。注意他的调用方式是先序列化再反序列化如果和原来的树相同的话就是正确的,所以中间返回的序列只要在反序列化时能解析就行,没有固定格式。

思路:序列化时按层遍历,用一个队列来保存当前节点。注意相对于普通的按层遍历,有一个条件不能少,就是在不能使用队列为null作为循环终止条件,因为最后一个叶子节点的左右子节点一定是null的,这样的话序列化的字符串就会多出来“null”,需要加一个判定有效节点个数的条件。如果非要使用队列为null作为唯一循环终止的条件的话就需要在反序列化时去掉序列最后所有的"null"。

AC代码:

 /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Codec { private int cnt;
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
nodeCount(root);
StringBuilder res = new StringBuilder();
Deque<TreeNode> queue = new LinkedList<TreeNode>();
if(root == null) {
return null;
} queue.offer(root);
int count = 0;
while(count < cnt && !queue.isEmpty()) { TreeNode node = queue.peek();
if(node == null) {
res.append("null ");
queue.poll();
}
else {
res.append(node.val + " ");
count ++;
queue.poll();
if(node.left != null) {
queue.offer(node.left);
}
else {
queue.offer(null);
}
if(node.right != null) {
queue.offer(node.right);
}
else {
queue.offer(null);
}
} }
return res.toString();
} public int treeDepth(TreeNode root) {
int dep = 0;
if(root != null) {
int leftDp = treeDepth(root.left);
int rightDp = treeDepth(root.right);
dep = leftDp>=rightDp? leftDp+1:rightDp+1;
}
return dep;
} public void nodeCount(TreeNode root) {
if(root != null) {
cnt ++;
nodeCount(root.left);
nodeCount(root.right);
} } // Decodes your encoded data to tree.
public TreeNode deserialize(String data) { if(data == null) {
return null;
} Deque<String> queue = new LinkedList<String>();
Deque<TreeNode> nodeQueue = new LinkedList<TreeNode>();
String[] spData = data.split(" ");
int i = spData.length - 1;
while(spData[i].equals("null")) i--;
for(int j=0; j<=i; j++) {
queue.offer(spData[j]);
} TreeNode root = new TreeNode(Integer.parseInt(queue.poll())); nodeQueue.offer(root); while(!queue.isEmpty()) {
TreeNode p = nodeQueue.poll();
String lc = queue.peek();
if(!queue.isEmpty()) {
queue.poll();
if(lc != null) {
if(!lc.equals("null")) {
TreeNode node = new TreeNode(Integer.parseInt(lc));
p.left = node;
nodeQueue.offer(node);
}
} } if(!queue.isEmpty()) {
String rc = queue.peek();
queue.poll();
if(rc != null) {
if(!rc.equals("null")) {
TreeNode node = new TreeNode(Integer.parseInt(rc));
p.right = node;
nodeQueue.offer(node);
}
}
}
}
return root;
}
} // Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));

LeetCode——Serialize and Deserialize Binary Tree的更多相关文章

  1. [LeetCode] Serialize and Deserialize Binary Tree

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

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

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

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

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

  4. [LeetCode] Serialize and Deserialize N-ary Tree N叉搜索树的序列化和去序列化

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

  5. LC 297 Serialize and Deserialize Binary Tree

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

  6. [LintCode] Serialize and Deserialize Binary Tree(二叉树的序列化和反序列化)

    描述 设计一个算法,并编写代码来序列化和反序列化二叉树.将树写入一个文件被称为“序列化”,读取文件后重建同样的二叉树被称为“反序列化”. 如何反序列化或序列化二叉树是没有限制的,你只需要确保可以将二叉 ...

  7. LeetCode OJ 297. Serialize and Deserialize Binary Tree

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

  8. LeetCode OJ:Serialize and Deserialize Binary Tree(对树序列化以及解序列化)

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

  9. 297. Serialize and Deserialize Binary Tree

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

随机推荐

  1. aehyok.com的成长之路三——框架结构

    前言 首先奉上个人网站地址传送门:aehyok.com. aehyok.com的成长之路一——开篇 中主要阐述了自己为什么建立自己的网站,以及个人网站的大致方向. aehyok.com的成长之路二—— ...

  2. Windows server 2008 R2充当路由器实现网络的互联(转)

    1.路由器的工作原理 当IP子网中的一台主机发送IP分组给同一IP子网的另一台主机时,它将直接把IP分组送到网络上,对方就能收到.而要送给不同IP子网上的主机时,它要 选择一个能到达目的子网上的路由器 ...

  3. 旧手机作为USB无线网卡使用(分享WIFI、蓝牙连接)

    首先开启手机的WIFI或者蓝牙功能,建立访问互联网的连接,然后设置-更多-网络共享与便携热点,打开安卓手机USB网络共享功能,即可在计算机上通过手机(无电话卡.数据卡)访问互联网.而且此时手机一直在充 ...

  4. ldr和adr在使用标号表达式作为操作数的区别

    ARM汇编有ldr指令以及ldr.adr伪指令,他门都可以将标号表达式作为操作数,下面通过分析一段代码以及对应的反汇编结果来说明它们的区别. ldr     r0, _start adr     r0 ...

  5. Activemq消息类型

    Activemq消息类型JMS规范中的消息类型包括TextMessage.MapMessage.ObjectMessage.BytesMessage.和StreamMessage等五种.ActiveM ...

  6. A cycle was detected in the build path of project

    解决Eclipse中Java工程间循环引用而报错的问题 如果我们的项目包含多个工程(project),而它们之间又是循环引用的关系,那么Eclipse在编译时会抛出如下一个错误信息: “A cycle ...

  7. web优化规范

    转载自:http://www.tuicool.com/articles/UZR3Az

  8. Java对象创建阶段的代码调用顺序

    在创建阶段系统通过下面的几个步骤来完成对象的创建过程 为对象分配存储空间 开始构造对象 从超类到子类对static成员进行初始化 超类成员变量按顺序初始化,递归调用超类的构造方法 子类成员变量按顺序初 ...

  9. 菜鸟类库诞生记二:通过反射转换DataRow为对象

    虽然大数据量的环境下,通过反射转换DataRow为对象性能会很低,但是在数据量适中的时候,这样能够减少很多的代码量,性能也确实不错. 所以在数据量不是很大的情况下,推荐使用. 如果数据量很大,可以使用 ...

  10. 关于DDD的 认识

    tks: 第一篇: 领域驱动设计系列(1)通过现实例子显示领域驱动设计的威力 第二篇: 领域驱动设计系列(2)浅析VO.DTO.DO.PO的概念.区别和用处 第三篇: 领域驱动设计系列(3)有选择性的 ...