题目链接:https://leetcode-cn.com/problems/serialize-and-deserialize-binary-tree/
解题步骤:
- 通过前序遍历将二叉树序列化为字符串,前序遍历顺序:根节点、左子树、右子树
- 节点间用","隔开,并用"null"表示空节点
- 使用递归,我们可以得到序列:“1,2,null,null,3,4,null,null,5,null,null,”
- 获得序列化字符串后,第一个值为根节点,接下来是左子树节点,右子树节点
- 所以我们可以依次取到节点的值,并使用前序遍历的方式,构建二叉树
C++实现:
/**
* 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:
void rserialize(TreeNode* root, string &str) {
if (root == nullptr)
str += "null,";
else {
str += (to_string(root->val) + ",");
rserialize(root->left, str);
rserialize(root->right, str);
}
}
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
string str = "";
rserialize(root, str);
return str;
}
TreeNode* rdeserialize(string &data, int &index) {
if (data[index] == 'n') { // 跳过null节点
index += 5;
return NULL;
}
int value = 0;
int flag = 1;
while (data[index] != ',') {
if (data[index] == '-'){ // 判断是否为负数
flag = -1;
index++;
}
value = 10 * value + (data[index] - '0');
index++;
}
index++;
TreeNode* root = new TreeNode(flag * value); // 根节点
root->left = rdeserialize(data, index); // 构建左子树
root->right = rdeserialize(data, index); // 构建右子树
return root;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
int index = 0;
return rdeserialize(data, index);
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));