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.

Credits:
Special thanks to @Louis1992 for adding this problem and creating all test cases.

【解析1】

其实LeetCode上树的表示方式就挺好,即"[1,2,3,null,null,4,5]"这种形式,我们接下来就实现以下这种序列化。

序列化比较容易,我们做一个层次遍历就好,空的地方用null表示,稍微不同的地方是题目中示例得到的结果是"[1,2,3,null,null,4,5,null,null,null,null,]",即 4 和 5 的两个空节点我们也存了下来。

饭序列化时,我们根据都好分割得到每个节点。需要注意的是,反序列化时如何寻找父节点与子节点的对应关系,我们知道在数组中,如果满二叉树(或完全二叉树)的父节点下标是 i,那么其左右孩子的下标分别为 2*i+1 和 2*i+2,但是这里并不一定是满二叉树(或完全二叉树),所以这个对应关系需要稍作修改。如下面这个例子:

       5
/ \
4 7
/ /
3 2
/ /
-1 9

序列化结果为[5,4,7,3,null,2,null,-1,null,9,null,null,null,null,null,]。

其中,节点 2 的下标是 5,可它的左孩子 9 的下标为 9,并不是 2*i+1=11,原因在于 前面有个 null 节点,这个 null 节点没有左右孩子,所以后面的节点下标都提前了2。所以我们只需要记录每个节点前有多少个 null 节点,就可以找出该节点的孩子在哪里了,其左右孩子分别为 2*(i-num)+1 和 2*(i-num)+2(num为当前节点之前 null 节点的个数)。

【java代码】非递归

 /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Codec { // Encodes a tree to a single string.
public String serialize(TreeNode root) {
StringBuilder sb = new StringBuilder();
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root); while (!queue.isEmpty()) {
TreeNode node = queue.poll();
if (node == null) {
sb.append("null,");
} else {
sb.append(String.valueOf(node.val) + ",");
queue.offer(node.left);
queue.offer(node.right);
}
} return sb.toString();
} // Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if (data == null || data.isEmpty()) return null; String[] vals = data.split(",");
int[] nums = new int[vals.length]; // 节点i之前null节点的个数
TreeNode[] nodes = new TreeNode[vals.length]; for (int i = 0; i < vals.length; i++) { //计算每个节点前面null节点的数目
if (i > 0) {
nums[i] = nums[i - 1];
}
if (vals[i].equals("null")) {
nodes[i] = null;
nums[i]++;
} else {
nodes[i] = new TreeNode(Integer.parseInt(vals[i]));
}
} for (int i = 0; i < vals.length; i++) { //对节点进行连接操作
if (nodes[i] == null) {
continue;
}
nodes[i].left = nodes[2 * (i - nums[i]) + 1];
nodes[i].right = nodes[2 * (i - nums[i]) + 2];
} return nodes[0];
} }

【解析2】

我们也可以用递归来解决这个问题:The idea is simple: print the tree in pre-order traversal and use "X" to denote null node and split node with ",". We can use a StringBuilder for building the string on the fly. For deserializing, we use a Queue to store the pre-order traversal and since we have "X" as null node, we know exactly how to where to end building subtress.

这个思路用到的是树的前序遍历,因为序列中包含了值为null的节点,因此我们可以很容易地进行反序列化操作。

【java代码】递归

 public class Codec {
private static final String spliter = ",";
private static final String NN = "X"; // Encodes a tree to a single string.
public String serialize(TreeNode root) {
StringBuilder sb = new StringBuilder();
buildString(root, sb);
return sb.toString();
} private void buildString(TreeNode node, StringBuilder sb) {
if (node == null) {
sb.append(NN).append(spliter);
} else {
sb.append(node.val).append(spliter);
buildString(node.left, sb);
buildString(node.right,sb);
}
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
Deque<String> nodes = new LinkedList<>();
nodes.addAll(Arrays.asList(data.split(spliter)));
return buildTree(nodes);
} private TreeNode buildTree(Deque<String> nodes) {
String val = nodes.remove();
if (val.equals(NN)) return null;
else {
TreeNode node = new TreeNode(Integer.valueOf(val));
node.left = buildTree(nodes);
node.right = buildTree(nodes);
return node;
}
}
}
 

LeetCode OJ 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. 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 ...

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

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

  4. LC 297 Serialize and Deserialize Binary Tree

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

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

  6. Leetcode 297. Serialize and Deserialize Binary Tree

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

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

  8. 297. Serialize and Deserialize Binary Tree

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

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

随机推荐

  1. mysql修改密码Your password does not satisfy the current policy requirements

    出现这个问题的原因是:密码过于简单.刚安装的mysql的密码默认强度是最高的,如果想要设置简单的密码就要修改validate_password_policy的值, validate_password_ ...

  2. 如何占用你用户的时间 and 如何提高客户的满意度 。 待续

    未来的商业竞争, 可能本质上是在争取客户的时间 嗯..有不定时, 未知的奖励,游戏行业就经常使用, 比如打怪掉装备, 不一定掉什么好东西, 让人充满了期待, 玛雅宝石, 有一定的概率... 觉得公司员 ...

  3. [笔记]The Linux command line

    Notes on The Linux Command Line (by W. E. Shotts Jr.) edited by Gopher 感觉博客园是不是搞了什么CSS在里头--在博客园显示效果挺 ...

  4. 验证码计时 -- UIButton setTitle 闪烁问题解决方案

    首先,有各种版本 方法一: 我运用的一种极其简单的版本:  将UIButton的Type 设成 Custom 就不会有闪烁的问题重现 p.p1 { margin: 0.0px 0.0px 0.0px ...

  5. Hibernate5--课程笔记1

    Hibernate简介: Hibernate是一个开放源代码的ORM(对象关系映射)框架,它对JDBC进行了非常轻量级的对象封装,使得Java程序员可以随心所欲的使用对象编程思维来操纵数据库. Hib ...

  6. scala调用外部命令

     scala调用外部命令 1.  导入sys.process包 2. 调用方式:" 外部命令 " !     双引号内+外部命令+感叹号 例:     scala调用外部命令工作原 ...

  7. ios隐藏软键盘

    //判断是否为苹果 var isIPHONE = navigator.userAgent.toUpperCase().indexOf('IPHONE')!= -1; // 元素失去焦点隐藏iphone ...

  8. 3、FileInputStream--->类文件输入流(读取文件数据)

    Api介绍 定义 FileInputStream 用于读取诸如图像数据之类的原始字节流.要读取字符流,请考虑使用 FileReader 构造方法 FileInputStream(File file) ...

  9. HDU_1245_Saving James Bond_最短路

    题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=1245 题意:给一个已知直径的圆形岛,然后岛的附近是湖,湖里有一些点,以坐标的形式给出,最外层是矩形的终 ...

  10. 8、Spring+Struts2+MyBaits(Spring注解+jdbc属性文件+log4j属性文件)

    一.注解理论 使用注解来构造IoC容器 用注解来向Spring容器注册Bean.需要在applicationContext.xml中注册<context:component-scan base- ...