AcWing 50. 序列化二叉树
原题链接
困难
作者:
NicoNicoNi
,
2021-03-10 18:27:00
,
所有人可见
,
阅读 449
C++ 代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
string res;
if(!root) return res;
queue<TreeNode*> lo;
lo.push(root);
while(!lo.empty())
{
auto node = lo.front();
lo.pop();
if(!node)
{
res+="#,";
}
else
{
res += (to_string(node->val) + ',');//res.push_back(',');
lo.push(node->left),lo.push(node->right);
}
}
return res;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string str) {
if(str.length() == 0 ) return nullptr;
string rootval = str.substr(0,str.find_first_of(','));
auto root = new TreeNode(stoi(rootval));
str = str.substr(str.find_first_of(',')+1);
queue<TreeNode*> tree;
tree.push(root);
while(!tree.empty() && !str.empty())
{
auto node = tree.front();
tree.pop();
if(str[0] == '#')
{
node->left = nullptr;
str = str.substr(str.find_first_of(',')+1);
}
else
{
int v = stoi(str.substr(0,str.find_first_of(',')));
node->left = new TreeNode(v);
tree.push(node->left);
str = str.substr(str.find_first_of(',')+1);
}
if(str[0] == '#')
{
node->right = nullptr;
str = str.substr(str.find_first_of(',')+1);
}
else
{
int v = stoi(str.substr(0,str.find_first_of(',')));
node->right = new TreeNode(v);
tree.push(node->right);
str = str.substr(str.find_first_of(',')+1);
}
}
return root;
}
};