To serialize and deserialize a binary tree in C, we can use a pre-order traversal with markers for null nodes. Here's a step-by-step implementation:
c Copy code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
typedef struct {
char* buffer;
int size;
int capacity;
} Buffer;
static void append(Buffer* buf, const char* s) {
int len = strlen(s);
if (buf->size + len + 1 > buf->capacity) {
buf->capacity = buf->capacity == 0 ? 256 : buf->capacity * 2;
char* new_buf = realloc(buf->buffer, buf->capacity);
if (!new_buf) return;
buf->buffer = new_buf;
}
strcpy(buf->buffer + buf->size, s);
buf->size += len;
}
static void serialize_helper(TreeNode* node, Buffer* buf) {
if (!node) {
append(buf, "# ");
return;
}
char val_str[20];
sprintf(val_str, "%d ", node->val);
append(buf, val_str);
serialize_helper(node->left, buf);
serialize_helper(node->right, buf);
}
char* serialize(TreeNode* root) {
Buffer buf = {0};
serialize_helper(root, &buf);
if (buf.size > 0 && buf.buffer[buf.size - 1] == ' ') {
buf.size--;
}
char* result = realloc(buf.buffer, buf.size + 1);
if (result) {
result[buf.size] = '\0';
} else {
free(buf.buffer);
return NULL;
}
return result;
}
TreeNode* deserialize_helper(char** tokens, int* index, int num_tokens) {
if (*index >= num_tokens) return NULL;
char* token = tokens[*index];
(*index)++;
if (strcmp(token, "#") == 0) return NULL;
TreeNode* node = malloc(sizeof(TreeNode));
if (!node) return NULL;
node->val = atoi(token);
node->left = deserialize_helper(tokens, index, num_tokens);
node->right = deserialize_helper(tokens, index, num_tokens);
return node;
}
TreeNode* deserialize(char* s) {
if (!s || *s == '\0') return NULL;
char* copy = strdup(s);
if (!copy) return NULL;
char* tokens[1000];
int num_tokens = 0;
char* token = strtok(copy, " ");
while (token) {
tokens[num_tokens++] = token;
token = strtok(NULL, " ");
}
int index = 0;
TreeNode* root = deserialize_helper(tokens, &index, num_tokens);
free(copy);
return root;
}
// Example usage
int main() {
// Construct sample tree: 1
// / \
// 2 3
// / \
// 4 5
TreeNode node5 = {5, NULL, NULL};
TreeNode node4 = {4, NULL, NULL};
TreeNode node3 = {3, &node4, &node5};
TreeNode node2 = {2, NULL, NULL};
TreeNode node1 = {1, &node2, &node3};
char* serialized = serialize(&node1);
printf("Serialized: %s\n", serialized); // Output: 1 2 # # 3 4 # # 5 # #
TreeNode* deserialized = deserialize(serialized);
// Further code to verify deserialization...
free(serialized);
// Free tree nodes here...
return 0;
}
This approach efficiently represents the tree structure and allows accurate reconstruction.