AcWing 50. 【二刷】剑指 Offer 37. 序列化二叉树
原题链接
困难
作者:
二十七杯酒
,
2021-04-01 10:46:48
,
所有人可见
,
阅读 452
C++(BFS)
class Codec {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
if(!root)return "";
string res = "";
res.append("[");
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
TreeNode *node = q.front();
q.pop();
if(node){
res.append(to_string(node->val));
q.push(node->left);
q.push(node->right);
}
else
res.append("null");
if(!q.empty())
res.push_back(',');
}
res.append("]");
return res;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
if(data.size() == 0)return NULL;
data = data.substr(1, data.size() - 2);
stringstream ss(data);
vector<string> encoder;
string str;
while(getline(ss, str, ',')){
encoder.push_back(str);
}
TreeNode *root = new TreeNode(stoi(encoder[0]));
queue<TreeNode*> q;
q.push(root);
int i = 1;
while(!q.empty()){
TreeNode* node = q.front();
q.pop();
if(encoder[i] != "null"){//千万记住是"null"而不是"NULL"...
node->left = new TreeNode(stoi(encoder[i]));
q.push(node->left);
}
i ++ ;
if(encoder[i] != "null"){
node->right = new TreeNode(stoi(encoder[i]));
q.push(node->right);
}
i ++ ;
}
return root;
}
};
C++(DFS)
class Codec {
public:
void dfs1(TreeNode* root, string& res){
if(!root){
res.append("null,");
return ;
}
res.append(to_string(root->val));
res.push_back(',');
dfs1(root->left, res);
dfs1(root->right, res);
return ;
}
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
string res;
dfs1(root, res);
return res;
}
TreeNode* dfs2(queue<string>& q){
if(!q.empty()){
string temp = q.front();
q.pop();
if(temp == "null")
return NULL;
TreeNode *root = new TreeNode(stoi(temp));
TreeNode *left = dfs2(q);
TreeNode *right = dfs2(q);
root->left = left;
root->right = right;
return root;
}
return NULL;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
if(data.size() == 0)return NULL;
cout << data << endl;
stringstream ss(data);
queue<string> encoder;
string str;
while(getline(ss, str, ',')){
encoder.push(str);
}
return dfs2(encoder);
}
};