設計一個算法,並編寫代碼來序列化和反序列化二叉樹。將樹寫入一個文件被稱爲“序列化”,讀取文件後重建同樣的二叉樹被稱爲“反序列化”。
如何反序列化或序列化二叉樹是沒有限制的,你只需要確保可以將二叉樹序列化爲一個字符串,並且可以將字符串反序列化爲原來的樹結構。
樣例
給出一個測試數據樣例, 二叉樹{3,9,20,#,#,15,7}
,表示如下的樹結構:
3
/ \
9 20
/ \
15 7
我們的數據是進行BFS遍歷得到的。當你測試結果wrong answer時,你可以作爲輸入調試你的代碼。
你可以採用其他的方法進行序列化和反序列化。
解題思路:和樣例一樣,使用BFS,先求得樹的深度(可由深度推出最大節點個數),然後用一個數組保存即可。
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
class Solution {
/**
* This method will be invoked first, you should design your own algorithm
* to serialize a binary tree which denote by a root node to a string which
* can be easily deserialized by your own "deserialize" method later.
*/
public String serialize(TreeNode root) {
// write your code here
if(root==null)
return "";
int deep = getDeepth(root);
int len = (int)Math.pow(2,deep)-1;
char[] arr = new char[len];
Arrays.fill(arr, '#');
fill(root, arr, 0);
return new String(arr);
}
private int getDeepth(TreeNode root){
if(root==null)
return 0;
return Math.max(getDeepth(root.left),getDeepth(root.right))+1;
}
private void fill(TreeNode root, char[] arr, int index){
if(root==null)
return;
arr[index] = (char)(root.val+'0');
fill(root.left, arr, 2*index+1);
fill(root.right,arr, 2*index+2);
}
/**
* This method will be invoked second, the argument data is what exactly
* you serialized at method "serialize", that means the data is not given by
* system, it's given by your own serialize method. So the format of data is
* designed by yourself, and deserialize it here as you serialize it in
* "serialize" method.
*/
public TreeNode deserialize(String data) {
// write your code here
if(data==null||data.length()==0)
return null;
return buildTree(data,0);
}
private TreeNode buildTree(String data, int id){
if(data.charAt(id)=='#')
return null;
TreeNode root = new TreeNode(data.charAt(id)-'0');
if(id*2+1 < data.length()){
root.left = buildTree(data, id*2+1);
root.right = buildTree(data, id*2+2);
}
return root;
}
}