AcWing 50. 序列化二叉树
原题链接
困难
作者:
王小强
,
2021-02-23 09:58:00
,
所有人可见
,
阅读 183
算法1: DFS
class Solution {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
if (!root) return "";
ostringstream out;
serialize(root, out);
return out.str();
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
if (data.empty()) return nullptr;
istringstream in(data);
return deserialize(in);
}
private:
void serialize(TreeNode* root, ostringstream& out) {
if (!root) {
out << "# ";
return;
}
out << to_string(root->val) << ' ';
serialize(root->left, out);
serialize(root->right, out);
}
TreeNode* deserialize(istringstream& in) {
string val;
in >> val;
if (val == "#") return nullptr;
auto root = new TreeNode(stoi(val));
root->left = deserialize(in);
root->right = deserialize(in);
return root;
}
};
TODO: 算法2 BFS