Serialization is the process of converting a data structure into a linear format that can be stored or transmitted, while deserialization is the reverse process of reconstructing the original data structure from the serialized format. Here's a step-by-step guide on how to serialize and deserialize a binary tree in C.
Serialization Approach:
We'll use a pre-order traversal (root, left, child) strategy for serialization. Each node will be represented as:
X for a null node ( sentinel value)
val for a non-null node, followed by its left and right child representations
Deserialization Approach:
During deserialization, we'll reconstruct the binary tree by parsing the serialized string from left to right, creating nodes as we encounter values, and assigning NULL when we hit the sentinel value X.
Implementation:
c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Define the structure for a binary tree node
typedef struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
// Function to create a new binary tree node
TreeNode* createNode(int val) {
TreeNode* newNode = (TreeNode*) malloc(sizeof(TreeNode));
if (!newNode) {
printf("Memory error\n");
return NULL;
}
newNode->val = val;
newNode->left = newNode->right = NULL;
return newNode;
}
// Serialize a binary tree into a string
void serialize(TreeNode* root, char** buf, int* buf_size, int* buf_capacity) {
if (root == NULL) {
// Append 'X' to indicate a null node
if (*buf_size + 2 > *buf_capacity) {
*buf_capacity *= 2;
*buf = realloc(*buf, *buf_capacity);
}
(*buf)[(*buf_size)++] = 'X';
(*buf)[(*buf_size)++] = ',';
return;
}
// Convert the node's value to string and append
int val_len = snprintf(NULL, 0, "%d", root->val);
if (*buf_size + val_len + 2 > *buf_capacity) {
*buf_capacity *= 2;
*buf = realloc(*buf, *buf_capacity);
}
*buf_size += sprintf(*buf + *buf_size, "%d,", root->val);
// Recursively serialize left and right subtrees
serialize(root->left, buf, buf_size, buf_capacity);
serialize(root->right, buf, buf_size, buf_capacity);
}
// Deserialize a string into a binary tree
TreeNode* deserialize(char** data) {
if (**data == 'X') {
// Skip 'X' and the following comma
(*data) += 2;
return NULL;
}
// Extract the node's value
int val = atoi(*data);
// Move the pointer past the value and the comma
while (**data != ',') (*data)++;
(*data)++;
TreeNode* node = createNode(val);
node->left = deserialize(data);
node->right = deserialize(data);
return node;
}
// Helper function to print the binary tree (in-order traversal)
void printTree(TreeNode* root) {
if (root) {
printTree(root->left);
printf("%d ", root->val);
printTree(root->right);
}
}
// Example usage
int main() {
// Construct a sample binary tree:
// 1
// / \
// 2 3
// / \
// 4 5
TreeNode* root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);
printf("Original tree (in-order traversal): ");
printTree(root);
printf("\n");
// Serialize the binary tree
int buf_capacity = 128;
int buf_size = 0;
char* serialized_tree = (char*) malloc(buf_capacity);
serialize(root, &serialized_tree, &buf_size, &buf_capacity);
serialized_tree[buf_size - 1] = '\0'; // Remove the trailing comma
printf("Serialized tree: %s\n", serialized_tree);
// Deserialize the string back into a binary tree
char* deserialization_ptr = serialized_tree;
TreeNode* deserialized_root = deserialize(&deserialization_ptr);
printf("Deserialized tree (in-order traversal): ");
printTree(deserialized_root);
printf("\n");
// Clean up dynamically allocated memory
free(serialized_tree);
// Note: You should also free the deserialized tree nodes to avoid memory leaks.
// For brevity, the deallocation code for the tree nodes is omitted here.
return 0;
}
Explanation:
serialize function:
Uses pre-order traversal to serialize the binary tree into a string.
X represents a null node, and actual node values are converted to strings and appended with a comma separator.
Dynamically resizes the buffer as needed to accommodate the serialized string.
deserialize function:
Parses the serialized string from left to right.
Creates a new node when encountering a value (until the next comma) and recursively deserializes its left and right children.
Skips X, to handle null nodes.
main function:
Demonstrates the serialization and deserialization process with a sample binary tree.
Prints the original and deserialized trees using in-order traversal for verification.
Output:
code
Original tree (in-order traversal): 4 2 5 1 3
Serialized tree: 1,2,4,X,X,5,X,X,3,X,X
Deserialized tree (in-order traversal): 4 2 5 1 3
This implementation showcases efficient serialization and deserialization of a binary tree in C, handling dynamic memory allocation and deallocation for the serialized string and tree nodes.
Time Complexity:
Serialization: O(N), where N is the number of nodes in the binary tree (each node is visited once).
Deserialization: O(N), as each character in the serialized string is processed exactly once.
Space Complexity:
O(N) for storing the serialized string (in the worst case, a skewed tree).
O(N) for the recursive call stack during serialization and deserialization.
O(N) for the deserialized binary tree itself.
Feel free to ask if you have any questions or need further clarification!