Serialize and Deserialize Binary Tree
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.
分析
类似于Tree的serialization最简单的方法还是依照某种遍历顺序用recursion来serialize。而因为deserialization来说preorder最方便,因为root很好找,总是第一个,所以我们优先选用preorder的遍历顺序完成serialization及deserialization。
关于deserialization, 我们可以用一个queue来存serialization的结果,每次deserialize的时候依次从queue中读取值来建node, 由于对null的node也serialize, 所以只要依照preorder的顺序deserialize, 不用担心queue中的node值与实际node不匹配。
这道题Follow up可以是N-ary Tree的serialization及deserialization, 或者类似html, xml的serialization
方法还是一样,依照某种遍历顺序用recursion来做。
复杂度
Serialization
time: O(n), space: O(1)
Deserialization
time: O(n), space: O(n)
代码
public class Codec {
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
if (root == null)
return "null";
StringBuilder sb = new StringBuilder();
sb.append(root.val);
String left = serialize(root.left);
String right = serialize(root.right);
sb.append(", "); // 用符号分开不同node值,方便deserialization
sb.append(left);
sb.append(", ");
sb.append(right);
return sb.toString();
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
// 把所有node依照preorder serialize后的结果依次存入queue中
Queue<String> q = new LinkedList<>();
String[] strs = data.split(", ");
for (String s : strs) {
q.add(s);
}
return helper(q);
}
// 从queue中依次取值建node, 顺序为preorder
public TreeNode helper(Queue<String> q) {
String s = q.remove();
if (s.equals("null"))
return null;
TreeNode root = new TreeNode(Integer.parseInt(s));
root.left = helper(q);
root.right = helper(q);
return root;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。