題目:
序列化是將一個數據結構或者對象轉換爲連續的比特位的操作,進而可以將轉換後的數據存儲在一個文件或者內存中,同時也可以通過網絡傳輸到另一個計算機環境,採取相反方式重構得到原數據。
請設計一個算法來實現二叉樹的序列化與反序列化。這裏不限定你的序列 / 反序列化算法執行邏輯,你只需要保證一個二叉樹可以被序列化爲一個字符串並且將這個字符串反序列化爲原始的樹結構。
示例:
你可以將以下二叉樹:
1
/ \
2 3
/ \
4 5
序列化爲 "[1,2,3,null,null,4,5]"
題解:
奧祕--BFS
代碼:
/**
* 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 ans = "[";
queue<TreeNode* >q;
q.push(root);
while(!q.empty())
{
int flag = 0;
queue<TreeNode*>q1;
while(!q.empty())
{
TreeNode* t = q.front();
q.pop();
if(!t) ans += "null,";
else
{
ans += to_string(t->val) + ",";
q1.push(t->left);
q1.push(t->right);
if(t->left || t->right) flag = 1;
}
}
if(flag)
{
while(!q1.empty())
{
TreeNode* t = q1.front();
q1.pop();
q.push(t);
}
}
}
ans = ans.substr(0,ans.size()-1);
ans = ans + "]";
return ans;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
for(int i = 0;i<data.size();i++)
{
if(data[i] == '[' || data[i] == ']' || data[i] == ',')
{
data[i] = ' ';
}
}
//處理字符串
stringstream ss(data);
string s;
vector<string>v;
while(ss >> s)
{
v.push_back(s);
}
TreeNode* root = NULL;
if(v[0] == "null") return root;
else
{
root = new TreeNode(atoi(v[0].c_str()));
}
queue<TreeNode*>q;
q.push(root);
int i = 1;
while(!q.empty() && i < v.size())
{
int len = q.size();
for(int j = 0;j<len;j++)
{
TreeNode* t = q.front();
q.pop();
if(v[i] != "null")
{
t->left = new TreeNode(atoi(v[i].c_str()));
}
i++;
if(v[i] != "null")
{
t->right = new TreeNode(atoi(v[i].c_str()));
}
i++;
if(t->left)
q.push(t->left);
if(t->right)
q.push(t->right);
}
}
return root;
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));