题目:
序列化是将一个数据结构或者对象转换为连续的比特位的操作,进而可以将转换后的数据存储在一个文件或者内存中,同时也可以通过网络传输到另一个计算机环境,采取相反方式重构得到原数据。
请设计一个算法来实现二叉树的序列化与反序列化。这里不限定你的序列 / 反序列化算法执行逻辑,你只需要保证一个二叉树可以被序列化为一个字符串并且将这个字符串反序列化为原始的树结构。
示例:
你可以将以下二叉树:
1
/
2 3
/
4 5
序列化为 "[1,2,3,null,null,4,5]"
提示: 这与 LeetCode 目前使用的方式一致,详情请参阅 LeetCode 序列化二叉树的格式。你并非必须采取这种方式,你也可以采用其他的方法解决这个问题。
说明: 不要使用类的成员 / 全局 / 静态变量来存储状态,你的序列化和反序列化算法应该是无状态的。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/serialize-and-deserialize-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:层次遍历即可,如果用满树去弄,很容易超内存。
注意使用istringstream 很容易将字符串分割。
/**
* 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) {
if (root == nullptr) return "";
queue<TreeNode*> q;
q.push(root);
stringstream ss;
while (!q.empty()) {
TreeNode* n = q.front();
q.pop();
if (n) {
ss << n->val << " ";
if (n->left) {
q.push(n->left);
} else {
q.push(nullptr);
}
if (n->right) {
q.push(n->right);
} else {
q.push(nullptr);
}
} else {
ss << "a ";
}
}
return ss.str();
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
//此处分隔字符串,有奇效。
std::istringstream iss(data);
std::vector<std::string> v(std::istream_iterator<std::string>{iss},
std::istream_iterator<std::string>());
int len = v.size();
if (len == 0) {
return nullptr;
}
queue<TreeNode*> q;
TreeNode* ret = new TreeNode(atoi(v[0].c_str()));
q.push(ret);
int idx = 1;
while (idx < len && !q.empty()) {
TreeNode* n = q.front();
q.pop();
auto s = v[idx];
if (s == "a") {
n->left = nullptr;
}
else {
TreeNode* ln = new TreeNode(atoi(v[idx].c_str()));
n->left = ln;
q.push(ln);
}
idx++;
if (idx >= len) break;
s = v[idx];
if (s == "a") {
n->right = nullptr;
}
else {
TreeNode* rn = new TreeNode(atoi(v[idx].c_str()));
n->right= rn;
q.push(rn);
}
idx++;
}
return ret;
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));