-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTreeSerialize.c
80 lines (70 loc) · 2.02 KB
/
TreeSerialize.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
//QUESTION: Serialize and deserialize a binary tree.
//CODE:
#include <stdio.h>
#include <stdlib.h>
// Define a structure for the binary tree node
struct TreeNode {
int data;
struct TreeNode* left;
struct TreeNode* right;
};
// Function to create a new tree node
struct TreeNode* createNode(int data) {
struct TreeNode* node = (struct TreeNode*)malloc(sizeof(struct TreeNode));
node->data = data;
node->left = NULL;
node->right = NULL;
return node;
}
// Function to serialize the tree (preorder traversal)
void serialize(struct TreeNode* root, FILE* file) {
if (root == NULL) {
fprintf(file, "# "); // Use # to represent NULL
return;
}
fprintf(file, "%d ", root->data);
serialize(root->left, file);
serialize(root->right, file);
}
// Function to deserialize the tree
struct TreeNode* deserialize(FILE* file) {
char buffer[10];
if (!fscanf(file, "%s", buffer) || buffer[0] == '#') {
return NULL;
}
struct TreeNode* root = createNode(atoi(buffer));
root->left = deserialize(file);
root->right = deserialize(file);
return root;
}
// Function to print the tree (inorder traversal)
void inorder(struct TreeNode* root) {
if (root == NULL) {
return;
}
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
int main() {
// Create a sample binary tree
struct TreeNode* root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);
root->right->left = createNode(6);
root->right->right = createNode(7);
// Serialize the tree to a file
FILE* file = fopen("tree.txt", "w");
serialize(root, file);
fclose(file);
// Deserialize the tree from the file
file = fopen("tree.txt", "r");
struct TreeNode* newRoot = deserialize(file);
fclose(file);
// Print the deserialized tree
printf("Inorder traversal of the deserialized tree:\n");
inorder(newRoot);
return 0;
}