Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
serialize-and-deserialize-binary-tree.cpp 2.92 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2015-10-26 21:54 +08:00 . Update serialize-and-deserialize-binary-tree.cpp
// Time: O(n)
// Space: O(h)
/**
* 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) {
string output;
serializeHelper(root, &output);
return output;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
TreeNode *root = nullptr;
int start = 0;
return deserializeHelper(data, &start);
}
private:
bool getNumber(const string &data, int *start, int *num) {
int sign = 1;
if (data[*start] == '#') {
*start += 2; // Skip "# ".
return false;
} else if (data[*start] == '-') {
sign = -1;
++(*start);
}
for (*num = 0; isdigit(data[*start]); ++(*start)) {
*num = *num * 10 + data[*start] - '0';
}
*num *= sign;
++(*start); // Skip " ".
return true;
}
void serializeHelper(const TreeNode *root, string *prev) {
if (!root) {
prev->append("# ");
} else {
prev->append(to_string(root->val).append(" "));
serializeHelper(root->left, prev);
serializeHelper(root->right, prev);
}
}
TreeNode *deserializeHelper(const string& data, int *start) {
int num;
if (!getNumber(data, start, &num)) {
return nullptr;
} else {
TreeNode *root = new TreeNode(num);
root->left = deserializeHelper(data, start);
root->right = deserializeHelper(data, start);
return root;
}
}
};
// Time: O(n)
// Space: O(n)
class Codec2 {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
ostringstream out;
serializeHelper(root, out);
return out.str();
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
istringstream in(data); // Space: O(n)
return deserializeHelper(in);
}
private:
void serializeHelper(const TreeNode *root, ostringstream& out) {
if (!root) {
out << "# ";
} else {
out << root->val << " ";
serializeHelper(root->left, out);
serializeHelper(root->right, out);
}
}
TreeNode *deserializeHelper(istringstream& in) {
string val;
in >> val;
if (val == "#") {
return nullptr;
} else {
TreeNode* root = new TreeNode(stoi(val));
root->left = deserializeHelper(in);
root->right = deserializeHelper(in);
return root;
}
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助