代码拉取完成,页面将自动刷新
// 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));
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。