【題目】
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 queue = new LinkedList();
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));