1 题目
对比“使用层序遍历的一个实现”:LeetCode-树-层序遍历(BFS)-二叉树的序列化与反序列化_hclbeloved的博客-CSDN博客
2 实现
// 此时使用的是 DFS
// 参考链接:https://leetcode-cn.com/problems/serialize-and-deserialize-binary-tree/solution/shou-hui-tu-jie-gei-chu-dfshe-bfsliang-chong-jie-f/
class Codec {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
if (!root)
return "null";
//使用前序遍历,是因为 根|左子树|右子树 的打印顺序,在反序列化时更容易定位出根节点的值。
string res(to_string(root->val));
res.append(1,',').append(serialize(root->left));
res.append(1,',').append(serialize(root->right));
return res;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
if (data.empty())
return NULL;
size_t pos = -1, lastPos = 0;
string str;
queue<string> q;
while ((pos = data.find(',', lastPos)) != string::npos)
{
str = data.substr(lastPos, pos - lastPos);
lastPos = pos + 1;
q.push(str);
}
str = data.substr(lastPos);
if (!str.empty())
{
q.push(str);
}
return buildTree(q);
}
TreeNode* buildTree(queue<string>& q)
{
string str = q.front();
q.pop();
if (str.compare("null") == 0)
return NULL;
TreeNode *root = new TreeNode(std::stoi(str));
root->left = buildTree(q);
root->right = buildTree(q);
return root;
}
};