題目
描述
設計一個算法,并編寫代碼來序列化和反序列化二叉樹。將樹寫入一個文件被稱為“序列化”,讀取文件后重建同樣的二叉樹被稱為“反序列化”。
如何反序列化或序列化二叉樹是沒有限制的,你只需要確保可以將二叉樹序列化為一個字符串,并且可以將字符串反序列化為原來的樹結構。
樣例
給出一個測試數據樣例, 二叉樹{3,9,20,#,#,15,7}
,表示如下的樹結構:
3
/ \
9 20
/ \
15 7
我們的數據是進行BFS遍歷得到的。當你測試結果wrong answer時,你可以作為輸入調試你的代碼。
你可以采用其他的方法進行序列化和反序列化。
解答
思路
基礎題。
開始忘了Queue類。手動寫字符串數組“彈出”的功能,很麻煩。查到Queue類就能很好的解決這個問題了。
代碼
/**
* 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 "#,";
// 新建StringBudffer,存儲節點值
StringBuffer sb = new StringBuffer(root.val+",");
// 遞歸左子樹
sb.append(serialize(root.left));
// 遞歸右子樹
sb.append(serialize(root.right));
// 返回StringBuffer的字符串值
return sb.toString();
}
/**
* 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
// 將在字符串按照','拆開成字符串數組
String[] ss = data.split(",");
// 用字符串數組構建字符串隊列
Queue<String> q = new LinkedList<String>();
for(int i = 0; i < ss.length; i++){
q.add(ss[i]);
}
// 遞歸生成二叉樹
return preOrder(q);
}
private TreeNode preOrder(Queue<String> q){
// “彈出”隊列下一個字符串
String val = q.poll();
// 如果值為'#'說明是空結點
if(val.equals("#")) return null;
// 如果值不為'#',用該值的整型值構建節點
TreeNode node = new TreeNode(Integer.valueOf(val));
// 遍歷構建節點左子樹
node.left = preOrder(q);
// 遍歷構建節點右子樹
node.right = preOrder(q);
// 返回節點
return node;
}
}