题目:

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.

链接: http://leetcode.com/problems/serialize-and-deserialize-binary-tree/

题解:

序列化Binary Tree。 这里因为给定的Tree的val是Integer,所以我们可以用一个字符型的常量当做delimiter,比如','。然后我们可以使用两种方法, pre-order traversal,或者level-order traversal。两种方法的时间复杂度和空间复杂度都一样。下面是pre-order traversal的:

Time Complexity - O(n), Space Compleixty - O(n)

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Codec {
private final String delimiter = ",";
private final String emptyNode = "#"; // Encodes a tree to a single string.
public String serialize(TreeNode root) {
StringBuilder sb = new StringBuilder();
serialize(root, sb);
return sb.toString();
} private void serialize(TreeNode root, StringBuilder sb) {
if(root == null) {
sb.append(emptyNode).append(delimiter);
} else {
sb.append(root.val).append(delimiter);
serialize(root.left, sb);
serialize(root.right, sb);
}
} // Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
Deque<String> nodes = new LinkedList<>();
nodes.addAll(Arrays.asList(data.split(delimiter)));
return deserialize(nodes);
} private TreeNode deserialize(Deque<String> nodes) {
String nodeVal = nodes.pollFirst();
if(nodeVal.equals(emptyNode)) {
return null;
} else {
TreeNode node = new TreeNode(Integer.parseInt(nodeVal));
node.left = deserialize(nodes);
node.right = deserialize(nodes);
return node;
}
}
} // Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));

二刷:

总的来说就是用in-order traversal来遍历。  Serialize的时候用一个StringBuilder保存。 Deserialize的时候先根据delimiter把元素都split到一个String[]数组里,然后可以把元素放入queue中,接下来递归使用in-order traversal方法来重建树。重建时每次从queue的前部poll()就可以了。

Java:

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Codec {
private final String delimiter = ",";
private final String nullNode = "#"; // Encodes a tree to a single string.
public String serialize(TreeNode root) {
StringBuilder sb = new StringBuilder();
serialize(root, sb);
//sb.setLength(sb.length() - 1);
return sb.toString();
} private void serialize(TreeNode root, StringBuilder sb) {
if (root == null) {
sb.append(nullNode).append(delimiter);
} else {
sb.append(root.val).append(delimiter);
serialize(root.left, sb);
serialize(root.right, sb);
}
} // Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if (data == null) return null;
String[] strs = data.split(delimiter);
Queue<String> q = new LinkedList<>();
Collections.addAll(q, strs);
return deserialize(q);
} private TreeNode deserialize(Queue<String> q) {
if (q.isEmpty()) return null;
String val = q.poll();
if (val.equals(nullNode)) return null;
TreeNode node = new TreeNode(Integer.valueOf(val));
node.left = deserialize(q);
node.right = deserialize(q);
return node;
}
} // Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));

三刷:

还是使用了in-order traversal。要注意delimiter假如使用'|'会报错,也不知道为什么。

Java:

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Codec {
private final String nullNode = "#";
private final String delimiter = ","; // Encodes a tree to a single string.
public String serialize(TreeNode root) {
StringBuilder sb = new StringBuilder();
serialize(root, sb);
return sb.toString();
} private void serialize(TreeNode root, StringBuilder sb) {
if (root == null) {
sb.append(nullNode).append(delimiter);
return;
}
sb.append(root.val).append(delimiter);
serialize(root.left, sb);
serialize(root.right, sb);
} // Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
Queue<String> q = new LinkedList<>();
Collections.addAll(q, data.split(delimiter));
return deserialize(q);
} private TreeNode deserialize(Queue<String> q) {
if (q.isEmpty()) return null;
String s = q.poll();
TreeNode root = null;
if (!s.equals(nullNode)) {
root = new TreeNode(Integer.valueOf(s));
root.left = deserialize(q);
root.right = deserialize(q);
}
return root;
}
} // Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));

Reference:

http://articles.leetcode.com/2010/09/serializationdeserialization-of-binary.html

http://articles.leetcode.com/2010/09/saving-binary-search-tree-to-file.html

https://leetcode.com/discuss/66147/recursive-preorder-python-and-c-o-n

https://leetcode.com/discuss/66117/easy-to-understand-java-solution

https://leetcode.com/discuss/66698/java-bfs-based-accepted-solution-using-queue

https://leetcode.com/discuss/66181/easy-to-understand-java-solution

https://leetcode.com/discuss/69390/simple-solution-%23preorder-traversal-%23recursive-%23simple-logic

https://leetcode.com/discuss/66077/c-accepted-o-n-easy-solution

https://leetcode.com/discuss/66397/java-stack-based-solution-using-json

https://leetcode.com/discuss/66076/java-solution-with-queue

https://leetcode.com/discuss/66625/a-level-order-traversal-solution

https://leetcode.com/discuss/66141/a-48-ms-rough-c-solution-used-queue

297. Serialize and Deserialize Binary Tree的更多相关文章

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

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

  2. LC 297 Serialize and Deserialize Binary Tree

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

  3. 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 ...

  4. [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 ...

  5. 297. Serialize and Deserialize Binary Tree *HARD*

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

  6. 297. Serialize and Deserialize Binary Tree二叉树的序列化和反序列化(就用Q)

    [抄题]: Serialization is the process of converting a data structure or object into a sequence of bits ...

  7. 【LeetCode】297. Serialize and Deserialize Binary Tree

    二叉树的序列化与反序列化. 如果使用string作为媒介来存储,传递序列化结果的话,会给反序列话带来很多不方便. 这里学会了使用 sstream 中的 输入流'istringstream' 和 输出流 ...

  8. 297 Serialize and Deserialize Binary Tree 二叉树的序列化与反序列化

    序列化是将一个数据结构或者对象转换为连续的比特位的操作,进而可以将转换后的数据存储在一个文件或者内存中,同时也可以通过网络传输到另一个计算机环境,采取相反方式重构得到原数据.请设计一个算法来实现二叉树 ...

  9. Leetcode 297. Serialize and Deserialize Binary Tree

    https://leetcode.com/problems/serialize-and-deserialize-binary-tree/ Serialization is the process of ...

随机推荐

  1. 寻找“水王”--c++

    一.题目与设计思路 三人行设计了一个灌水论坛.信息学院的学生都喜欢在上面交流灌水,传说在论坛上有一个“水王”,他不但喜欢发帖,还会回复其他ID发的每个帖子.坊间风闻该“水王”发帖数目超过了帖子数目的一 ...

  2. j2SE基回顾(一)

    1. 九种基本数据类型的大小,以及他们的封装类. 2. Switch能否用string做参数? 3. equals与==的区别. 4. Object有哪些公用方法? Object是所有类的父类,任何类 ...

  3. linux I/O

    一) I/O调度程序的总结     1) 当向设备写入数据块或是从设备读出数据块时,请求都被安置在一个队列中等待完成.     2) 每个块设备都有它自己的队列.     3) I/O调度程序负责维护 ...

  4. 【Java】Eclipse导出jar包与javadoc

    1.导出jar包 2.导出javadoc 3.jar包添加javadoc 4.出错解决 参考资料: http://www.cnblogs.com/cyh123/p/3345889.html http: ...

  5. UVA 10004 Bicoloring

    题目链接:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=12&pa ...

  6. [错误代码:0x80070002]IIS7及以上伪静态报错404

    故障现象:DTCMS开启伪静态功能,VS2010预览正常,发布到IIS后报错404.0错误 (WIN7,WIN8,SERVER2008).模块IISWebCore通知MapRequestHandler ...

  7. [百度空间] [原]跨平台编程注意事项(二): windows下 x86到x64的移植

    之前转的: 将程序移植到64位Windows 还有自己乱写的一篇: 跨平台编程注意事项(一) 之前对于x64平台的移植都是纸上谈兵,算是前期准备工作, 但起码在写代码时,已经非常注意了.所以现在移植起 ...

  8. 利用PE数据目录的导入表获取函数名及其地址

    PE文件是以64字节的DOS文件头开始的(IMAGE_DOS_HEADER),接着是一段小DOS程序,然后是248字节的 NT文件头(IMAGE_NT_HEADERS),NT的文件头位置由IMAGE_ ...

  9. C++中static的全部作用

    要理解static,就必须要先理解另一个与之相对的关键字,很多人可能都还不知道有这个关键字,那就是auto,其实我们通常声明的不用static修饰的变量,都是auto的,因为它是默认的,就象short ...

  10. poj 3254

    状态压缩 dp dp[i][j] 为第 i 行状态为 j 的总数 #include <cstdio> #include <cstdlib> #include <cmath ...