LeetCode——Serialize and Deserialize Binary Tree
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的更多相关文章
- [LeetCode] Serialize and Deserialize Binary Tree
Serialize and Deserialize Binary Tree Serialization is the process of converting a data structure or ...
- [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 N-ary Tree N叉搜索树的序列化和去序列化
Serialization is the process of converting a data structure or object into a sequence of bits so tha ...
- LC 297 Serialize and Deserialize Binary Tree
问题: Serialize and Deserialize Binary Tree 描述: Serialization is the process of converting a data stru ...
- [LintCode] Serialize and Deserialize Binary Tree(二叉树的序列化和反序列化)
描述 设计一个算法,并编写代码来序列化和反序列化二叉树.将树写入一个文件被称为“序列化”,读取文件后重建同样的二叉树被称为“反序列化”. 如何反序列化或序列化二叉树是没有限制的,你只需要确保可以将二叉 ...
- 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 ...
- 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 ...
- 297. Serialize and Deserialize Binary Tree
题目: Serialization is the process of converting a data structure or object into a sequence of bits so ...
随机推荐
- AP6181 正基 WIFI 模块
a. Module size: 12*12mm (pin to pin compatible) Package: Stamp type 44pins AP6181: WiFiAP6210: WiFi/ ...
- 【迁移】—Entity Framework实例详解
好久没有在博客园更新博客了,如今都换了新公司.前段时间写了关于EF迁移的文档,今天拿出来作为这个系列的一篇吧. 一.Entity Framework 迁移命令(get-help EntityFrame ...
- Linux安全事件应急响应排查方法总结
Linux安全事件应急响应排查方法总结 Linux是服务器操作系统中最常用的操作系统,因为其拥有高性能.高扩展性.高安全性,受到了越来越多的运维人员追捧.但是针对Linux服务器操作系统的安全事件也非 ...
- 解决genemotion模拟器冲突导致的Android Studio无法启动ADB的问题
首先命令行下运行 adb nodaemon server ./adb nodaemon server (Mac OSX) 如果出现错误: error: could not install *smart ...
- metaq安装实例
下载metaq: http://fnil.net/downloads/index.html 安装metaq: [root@localhost software]# pwd /export/softwa ...
- linux 下 取进程占用内存(MEM)最高的前10个进程
# linux 下 取进程占用 cpu 最高的前10个进程ps aux|head -1;ps aux|grep -v PID|sort -rn -k +3|head # linux 下 取进程占用内存 ...
- WP-PostViews的安装和设置方法
wordpress本身并没有文章浏览统计功能,必须借助插件.想要知道自己的文章被多数访客浏览,或者访客对哪些文章或者哪类文章更加有兴趣,这就是文章统计的重要性了.WP-PostViews插件是哥不错的 ...
- 防抖(Debounce)与节流( throttle)区别
http://www.cnblogs.com/ShadowLoki/p/3712048.html http://blog.csdn.net/tina_ttl/article/details/51830 ...
- 移动应用安全开发指南(Android)--完结篇(http://www.bubuko.com/infodetail-577312.html)
1.认证和授权 概述 认证是用来证明用户身份合法性的过程,授权是用来证明用户可以合法地做哪些事的过程,这两个过程一般是在服务器端执行的,但也有的APP出于性能提升或用户体验等原因,将其做在客户端完成, ...
- 面向.Net程序员的后端性能优化实战
最近2个月没做什么新项目 完全是对于旧的系统进行性能优化 避免超时 死锁 数据处理能力不够等常见的性能问题 这里不从架构方面出发 毕竟动大手脚成本比较高 那么我们以实例为前提 从细节开始 优化角度 一 ...