Steward
分享是一種喜悅、更是一種幸福
程式語言 - LeetCode - C++ - 449. Serialize and Deserialize BST
參考資訊:
https://www.cnblogs.com/grandyang/p/6224510.html
題目:

解答:
/**
* 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) {
ostringstream os;
auto dfs = [&](this auto&& dfs, TreeNode *n) {
if (!n) {
os << "# ";
return;
}
os << n->val << " ";
dfs(n->left);
dfs(n->right);
};
dfs(root);
return os.str();
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
istringstream is(data);
auto dfs = [&](this auto&& dfs) -> TreeNode* {
string t = "";
is >> t;
if (t == "#") {
return nullptr;
}
TreeNode *n = new TreeNode(stoi(t));
n->left = dfs();
n->right = dfs();
return n;
};
return dfs();
}
};
// Your Codec object will be instantiated and called as such:
// Codec* ser = new Codec();
// Codec* deser = new Codec();
// string tree = ser->serialize(root);
// TreeNode* ans = deser->deserialize(tree);
// return ans;