题目:序列化二叉树
请实现两个函数,分别用来序列化和反序列化二叉树。
示例:
你可以将以下二叉树:
1
/ \
2 3
/ \
4 5
序列化为 "[1,2,3,null,null,4,5]"
解题:
/**
* 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 {
private:
// 1,2,#,#,3,-4,#,#,5,#,#,
void encode(TreeNode* root, string& res) {
if (!root) {
res += "#,";
return;
}
res += to_string(root->val) + ",";
encode(root->left, res);
encode(root->right, res);
}
TreeNode* decode(int& p, const string& data) {
if (data[p] == '#') {
p += 2;
return NULL;
}
bool isN = false;
if (data[p] == '-') { // 负数的情况
isN = true;
p++;
}
int num = 0; // 还原成整数
while (data[p] != ',') {
num = num * 10 + data[p] - '0';
p++;
}
p++;
if (isN) num = -num;
auto root = new TreeNode(num);
root->left = decode(p, data);
root->right = decode(p, data);
return root;
}
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
string res = "";
encode(root, res);
return res;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
int p = 0;
return decode(p, data);
}
};
来源:CSDN
作者:CG&AR Player
链接:https://blog.csdn.net/qq_41598072/article/details/104598811