二叉树的序列化和反序列化c语言代码
时间: 2023-09-04 12:11:03 浏览: 92
以下是二叉树的序列化和反序列化的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STR_LEN 1000
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
char *serialize(TreeNode *root) {
if (root == NULL) {
char *str = (char *)malloc(sizeof(char) * 2);
strcpy(str, "#");
return str;
}
char *left_str = serialize(root->left);
char *right_str = serialize(root->right);
char *str = (char *)malloc(sizeof(char) * MAX_STR_LEN);
sprintf(str, "%d,%s,%s", root->val, left_str, right_str);
free(left_str);
free(right_str);
return str;
}
TreeNode *deserialize(char *str) {
if (*str == '#') {
return NULL;
}
int val = 0;
while (*str != ',') {
val = val * 10 + (*str - '0');
str++;
}
str++;
TreeNode *node = (TreeNode *)malloc(sizeof(TreeNode));
node->val = val;
node->left = deserialize(str);
while (*str != ',') {
str++;
}
str++;
node->right = deserialize(str);
return node;
}
void print_tree(TreeNode *root) {
if (root == NULL) {
printf("# ");
return;
}
printf("%d ", root->val);
print_tree(root->left);
print_tree(root->right);
}
int main() {
TreeNode *root = (TreeNode *)malloc(sizeof(TreeNode));
root->val = 1;
root->left = (TreeNode *)malloc(sizeof(TreeNode));
root->left->val = 2;
root->left->left = NULL;
root->left->right = NULL;
root->right = (TreeNode *)malloc(sizeof(TreeNode));
root->right->val = 3;
root->right->left = (TreeNode *)malloc(sizeof(TreeNode));
root->right->left->val = 4;
root->right->left->left = NULL;
root->right->left->right = NULL;
root->right->right = (TreeNode *)malloc(sizeof(TreeNode));
root->right->right->val = 5;
root->right->right->left = NULL;
root->right->right->right = NULL;
printf("Original Tree: ");
print_tree(root);
printf("\n");
char *str = serialize(root);
printf("Serialized Tree: %s\n", str);
TreeNode *new_root = deserialize(str);
printf("Deserialized Tree: ");
print_tree(new_root);
printf("\n");
return 0;
}
```
在这个代码中,我们定义了一个 `TreeNode` 结构体,代表二叉树的节点。`serialize()` 函数实现了将二叉树序列化为字符串的功能,其中我们使用了递归的方式来遍历整个二叉树。`deserialize()` 函数实现了将字符串反序列化为二叉树的功能,同样使用了递归的方式。`print_tree()` 函数用于打印二叉树。在 `main()` 函数中,我们构造了一个二叉树,并测试了 `serialize()` 和 `deserialize()` 函数的正确性。
阅读全文