題目鏈接: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 5as
"[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.
題目要求對一個用TreeNode鏈表存儲的二叉樹進行序列化與反序列化,最後得到原始的TreeNode鏈表則說明成功。
因爲題目並不關心中間過程得到的序列化串,因此不必拘泥於LeetCode常用的表示法,而可以使用自己的表示法。
爲了方便重建,我們使用前序遍歷,並且每當碰到一個NULL孩子,就存儲一個#字符。
這樣來說,在存儲題目給出的樹的時候,我們會得到[1,2,#,#,3,4,#,#,5,#,#,]這麼一個字符串。
在還原時,只需要按照前序遍歷的方式遞歸着解析這個序列化串,使用的核心方法爲字符串的substr、find方法,該方法常用的形式有兩種:①str.substr(location),這個方法會返回str從location開始到結尾的字串。②str.substr(location,len),這個方法會返回[location,location+len)區間的字符串,注意右面爲開區間。str.find(charset)將返回str中第一個匹配到的charset的位置。
【具體實現】
爲了方便遞歸,我們定義兩個類的私有方法。
1.序列化
按照前序遍歷的規則訪問root,對於root爲NULL的情況拼接#,其他情況拼接結點的數字,爲了實現數字到字符串的轉換,使用stringstream。
2.反序列化
遞歸函數的參數爲(TreeNode *&root, string &data),根據data分割出的值val來決定root的值,如果val是#,則說明這是一個空結點,直接令root=NULL,否則創建一個新的TreeNode作爲root,注意解析val值使用的是C函數atoi,需要用字符串的c_str()方法得到char*字符串,繼續遞歸root的左右兒子,注意此時傳入的data是已經去掉處理完部分的字串。反序列化的遞歸順序與前序遍歷保持一致。
代碼如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Codec {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
string res;
preOrderSerialize(root,res);
cout << res;
return res;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
TreeNode *root = NULL;
preOrderDeserialize(root,data);
return root;
}
private:
void preOrderSerialize(TreeNode *root, string &str){
if(!root){
str += "#,";
return;
}
stringstream ss;
ss << root->val;
str += ss.str();
str += ",";
preOrderSerialize(root->left,str);
preOrderSerialize(root->right,str);
}
void preOrderDeserialize(TreeNode *&root, string &data){
if(data.length() == 0) return;
string tmp = data.substr(0,data.find(','));
data = data.substr(data.find(',')+1);
if(tmp.compare("#") == 0) root = NULL;
else{
root = new TreeNode(atoi(tmp.c_str()));
preOrderDeserialize(root->left,data);
preOrderDeserialize(root->right,data);
}
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));