fork download
  1. #include <stdio.h>
  2. #define MARKER -1
  3.  
  4. /* A binary tree Node has key, pointer to left and right children */
  5. struct Node
  6. {
  7. int key;
  8. struct Node* left, *right;
  9. };
  10.  
  11. /* Helper function that allocates a new Node with the
  12. given key and NULL left and right pointers. */
  13. Node* newNode(int key)
  14. {
  15. Node* temp = new Node;
  16. temp->key = key;
  17. temp->left = temp->right = NULL;
  18. return (temp);
  19. }
  20.  
  21. // This function stores a tree in a file pointed by fp
  22. void serialize(Node *root, FILE *fp)
  23. {
  24. // If current node is NULL, store marker
  25. if (root == NULL)
  26. {
  27. fprintf(fp, "%d ", MARKER);
  28. return;
  29. }
  30.  
  31. // Else, store current node and recur for its children
  32. fprintf(fp, "%d ", root->key);
  33. serialize(root->left, fp);
  34. serialize(root->right, fp);
  35. }
  36.  
  37. // This function constructs a tree from a file pointed by 'fp'
  38. Node *deSerialize(Node *root, FILE *fp)
  39. {
  40. // Read next item from file. If theere are no more items or next
  41. // item is marker, then return
  42. int val;
  43. if ( !fscanf(fp, "%d ", &val) || val == MARKER)
  44. return NULL;
  45.  
  46. // Else create node with this item and recur for children
  47. root = newNode(val);
  48. root->left = deSerialize(root->left, fp);
  49. root->right = deSerialize(root->right, fp);
  50. return root;
  51. }
  52.  
  53. // A simple inorder traversal used for testing the constructed tree
  54. void inorder(Node *root)
  55. {
  56. if (root)
  57. {
  58. inorder(root->left);
  59. printf("%d ", root->key);
  60. inorder(root->right);
  61. }
  62. }
  63.  
  64. /* Driver program to test above functions*/
  65. int main()
  66. {
  67. // Let us construct a tree shown in the above figure
  68. struct Node *root = newNode(20);
  69. root->left = newNode(8);
  70. root->right = newNode(22);
  71. root->left->left = newNode(4);
  72. root->left->right = newNode(12);
  73. root->left->right->left = newNode(10);
  74. root->left->right->right = newNode(14);
  75.  
  76. // Let us open a file and serialize the tree into the file
  77. FILE *fp = fopen("tree.txt", "w");
  78. if (fp == NULL)
  79. {
  80. puts("Could not open file");
  81. return 0;
  82. }
  83. serialize(root, fp);
  84. fclose(fp);
  85.  
  86. // Let us deserialize the storeed tree into root1
  87. Node *root1 = NULL;
  88. fp = fopen("tree.txt", "r");
  89. root1 = deSerialize(root1, fp);
  90.  
  91. printf("Inorder Traversal of the tree constructed from file:\n");
  92. inorder(root1);
  93.  
  94. return 0;
  95. }
Success #stdin #stdout 0s 3456KB
stdin
Standard input is empty
stdout
Could not open file