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. Express ejs 3.* layout.ejs

    新版本改成了 <%- include file.ejs %> 具体使用方法如下:1. views文件夹 下新建header.ejs,插入代码 <html><head> ...

  2. Scala 深入浅出实战经典 第78讲:Type与Class实战详解

    王家林亲授<DT大数据梦工厂>大数据实战视频 Scala 深入浅出实战经典(1-87讲)完整视频.PPT.代码下载: 百度云盘:http://pan.baidu.com/s/1c0noOt ...

  3. 用ASP.NET Core 1.0中实现邮件发送功能

    准备将一些项目迁移到 asp.net core 先从封装类库入手,在遇到邮件发送类时发现在 asp.net core 1.0中并示提供SMTP相关类库,于是网上一搜发现了MailKit 好东西一定要试 ...

  4. 使用Microsoft.Office.Interop.Excel.Application xlApp 生成Excel

    object filePath = @"C:\" + DateTime.Now.ToShortDateString().Replace("-", "& ...

  5. Android xml 格式 随笔

    打包的时候Android xml文件会由字符格式(utf-8编码)转换为二进制格式.具体如:http://blog.csdn.net/jiangwei0910410003/article/detail ...

  6. 给VMware下的Linux扩展磁盘空间(以CentOS6.3为例)转

    #查看挂载点:df -h#显示:文件系统 容量 已用 可用 已用%% 挂载点/dev/mapper/vg_dc01-lv_root 47G 12G 34G 25% /tmpfs 504M 88K 50 ...

  7. 修改 Semantic UI 的默认字体

    Semantic UI 默认使用的是谷歌提供的字体,并且是直接使用了谷歌的官方链接.由于大家都知道的原因,谷歌网站在国内访问速度很差,甚至根本无法访问,还有就是可能会在离线环境下使用 Semantic ...

  8. Openvswitch原理与代码分析(6):用户态流表flow table的操作

    当内核无法查找到流表项的时候,则会通过upcall来调用用户态ovs-vswtichd中的flow table. 会调用ofproto-dpif-upcall.c中的udpif_upcall_hand ...

  9. C#导出EXCEL的几种方法

    using System; using System.Collections.Generic; using System.Text; using System.Data; using System.W ...

  10. android 开发 - 网络图片加载库 Fresco 的使用。

    概述 Fresco 是 facebook 的开源类库,它支持更有效的加载网络图片以及资源图片.它自带三级缓存功能,让图片显示更高效. 介绍 Fresco 是一个强大的图片加载组件. Fresco 中设 ...