题目链接: leetcode.
本题的测试的是 序列化 和 反序列化是否可逆,因此序列化列表的形式并未限制,只要两个函数可以互逆就好啦
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
/*
深度优先和广度优先都可以,试试广度吧,刚好可以层次遍历
执行用时:36 ms, 在所有 C++ 提交中击败了99.03%的用户
内存消耗:28.3 MB, 在所有 C++ 提交中击败了96.07%的用户
*/
class Codec {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
if(root == nullptr)
return "";
queue<TreeNode*> Q;
Q.push(root);
string ans = "";
while(!Q.empty())
{
TreeNode* node = Q.front();
Q.pop();
if(node == nullptr)
ans += "null,";
else
{
ans += to_string(node -> val);
ans += ",";
Q.push(node -> left);
Q.push(node -> right);
}
}
return ans;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
if(data.empty())
return NULL;
int N = data.size();
int start = 0, end = 0;
string tmp = select_num(data, start, end);
TreeNode* root = new TreeNode(stoi(tmp));
queue<TreeNode*> Q;
Q.push(root);
while(start < N)
{
TreeNode* node = Q.front();
Q.pop();
tmp = select_num(data, start, end);
if(tmp != "null")
{
node -> left = new TreeNode(stoi(tmp));
Q.push(node -> left);
}
tmp = select_num(data, start, end);
if(tmp != "null")
{
node -> right = new TreeNode(stoi(tmp));
Q.push(node -> right);
}
}
return root;
}
string select_num(const string& data, int& start, int& end)
{
while(data[end] != ',')
end++;
string tmp = data.substr(start, end - start);
start = ++end;
return tmp;
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));
string substr (size_t pos = 0, size_t len = npos) const;
子字符串是string对象的一部分,从字符位置pos开始并跨越len个字符(或直到字符串的结尾,以先到者为准)。
std::string str="We think in generalities, but we live in details.";
std::string str2 = str.substr (3,5); // "think"
这篇博客介绍了如何使用广度优先搜索实现二叉树的序列化和反序列化,确保序列化过程可逆。在C++中,通过层次遍历的方式将二叉树转化为字符串,并能根据该字符串重建原来的二叉树结构。代码执行效率高,内存占用少。

被折叠的 条评论
为什么被折叠?



