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 ...
随机推荐
- 将数据导出到Excel2007格式。
增加数据格式 public static void TableToExcel2(DataTable table, string filename, string sheetname) { XSSFWo ...
- java匹配中文的正则表达式
[\u4E00-\u9FA5]* public static void regxChinese(){ // 要匹配的字符串 String source = "<span title=' ...
- windows下搭建学习objective-c 的运行环境【转载】
对于Iphone开发学习者而言,Object -c 是必修的语言.但是由于苹果的自我封闭的产业链发展模式(从芯片.机器.开发语言.终端产品.服务)的限制,要想开发针对苹果iPhone等产品的应用程序, ...
- Scala 深入浅出实战经典 第78讲:Type与Class实战详解
王家林亲授<DT大数据梦工厂>大数据实战视频 Scala 深入浅出实战经典(1-87讲)完整视频.PPT.代码下载: 百度云盘:http://pan.baidu.com/s/1c0noOt ...
- Scala 深入浅出实战经典 第60讲:Scala中隐式参数实战详解以及在Spark中的应用源码解析
王家林亲授<DT大数据梦工厂>大数据实战视频 Scala 深入浅出实战经典(1-87讲)完整视频.PPT.代码下载:百度云盘:http://pan.baidu.com/s/1c0noOt6 ...
- go2shell的安装与修改默认terminal方法
go2shell的安装与修改默认terminal方法 1. 安装go2shell后,打开finder的application文件夹,找到go2shell 2. 按住command,用鼠标将go2s ...
- Why GUID primary keys are a database’s worst nightmare
http://csharptest.net/1250/why-guid-primary-keys-are-a-databases-worst-nightmare/ When you ask most ...
- Struts2返回json
Action怎么返回json类型数据?方法1,使用struts2的插件struts2-json-plugin-2.3.8.jar(在下载的strut2库文件夹中). 在struts2.xml中对要返回 ...
- 解决play-1.4.0在linux或mac下提示No such file or directory的问题
问题原因:"play"脚本中有特殊符号. 解决方案:写脚本去掉即可. 代码:fixplay.py 放在play-1.4.0目录下执行.亲测在osx与ubuntu下均可用. with ...
- Windows Store 开发总结——文件操作
1.读取Isolated Storage 每个Metro程序都有三个文件夹:Local,Roaming,Temp.每个文件夹的访问方法都是相同的. Local用于将数据存储在本地,这是程序特定的文件夹 ...