【LeetCode】Serialize and Deserialize Binary Tree 解题报告
2015-10-28 21:38
337 查看
【题目】
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
as
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.
【解析】
其实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,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.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++) {
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];
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));
这道题比较简洁的写法是递归,参见https://leetcode.com/discuss/66117/easy-to-understand-java-solution。
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.
【解析】
其实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.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++) {
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];
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));
这道题比较简洁的写法是递归,参见https://leetcode.com/discuss/66117/easy-to-understand-java-solution。
相关文章推荐
- 05-树9 Huffman Codes
- fragment 的repalce方法和hide和show
- hdu 4633 Who's Aunt Zhang(polya)
- cxf 创建动态webService
- 将中缀表达式转化为后缀表达式
- Mondrian 使用教程
- 约瑟夫环问题之选猴王
- 约瑟夫环问题之选猴王
- Android学习笔记之Activity Intent 数据传输之回传结果
- C-结构
- c# 语言基础
- CSS3实现精美的纸张折角效果 -- 进阶版
- CSS3实现精美的纸张折角效果 -- 进阶版
- struts2基于xml配置文件的用户验证方法
- 虚拟机vmware中ubuntu不能上网解决方法
- UML
- java之JDBC
- Jquery选择器
- [学习OpenCV攻略][007][缩小图片]
- UNITY 5.2 Application类