fork download
  1. #include"stdio.h"
  2. #include"stdlib.h"
  3. #define N 3
  4. struct node
  5. {
  6. int info;
  7. struct node *child[N];
  8. };
  9. struct node *Root=NULL,*dRoot=NULL;
  10. int dIndex=0,sIndex=0;
  11. struct node* createNode(int data) //Function to create a new node
  12. {
  13. struct node * root;
  14. root=(struct node*)malloc(sizeof(struct node));
  15. root->info=data;
  16. for(int k=0;k<N;k++)
  17. root->child[k]=NULL;
  18. return root;
  19. }
  20. struct node * createTree() //Function to create Tree
  21. {
  22. struct node * root;
  23. root=createNode(28);
  24. root->child[0]=createNode(22);
  25. root->child[1]=createNode(8);
  26. root->child[2]=createNode(12);
  27. root->child[0]->child[0]=createNode(2);
  28. root->child[0]->child[1]=createNode(7);
  29. root->child[1]->child[0]=createNode(13);
  30. root->child[2]->child[0]=createNode(19);
  31. root->child[2]->child[1]=createNode(25);
  32. root->child[2]->child[2]=createNode(24);
  33. return root;
  34. }
  35. void serialize(struct node* root,int arr[]) //Function to serialize Tree
  36. {
  37. if(root==NULL)
  38. {
  39. arr[sIndex]=-1;
  40. sIndex++;
  41. return;
  42. }
  43. arr[sIndex]=root->info;
  44. sIndex++;
  45. for(int k=0;k<N;k++)
  46. serialize(root->child[k],arr);
  47. }
  48. struct node* deserialize(struct node * root,int arr[]) //Function for deserialization
  49. {
  50. if(arr[dIndex]==(-1) || dIndex==sIndex-1)
  51. {
  52. dIndex++;
  53. return NULL;
  54. }
  55. root=createNode(arr[dIndex]);
  56. dIndex++;
  57. for(int k=0;k<N;k++)
  58. {
  59. root->child[k]=deserialize(root->child[k],arr);
  60. }
  61. return root;
  62. }
  63. void Travers(struct node* root) //Function to traverse Tree
  64. {
  65. if(root==NULL)
  66. return;
  67. printf(" %d",root->info);
  68. for(int k=0;k<N;k++)
  69. Travers(root->child[k]);
  70. }
  71. void main(){
  72. int array[50];
  73. Root=createTree(); //Creating Tree and address of root node returns to Root pointer
  74. printf("The elements of created tree : ");
  75. Travers(Root); //Displaying the tree by traversing
  76. serialize(Root,array); //Serialize the tree
  77. printf("\nThe elements of tree in serialized form : ");
  78. for(int j=0;j<sIndex;j++)
  79. printf("%d ",array[j]); //Displaying the Tree in serialized form
  80. printf(" \nThe elements of tree in deserialized form : ");
  81. dRoot=deserialize(dRoot,array); //Deserialing
  82. Travers(dRoot); //Displaying the Tree after retrieving after deserialization
  83. }
Runtime error #stdin #stdout 0s 4540KB
stdin
Standard input is empty
stdout
The elements of created tree :  28 22 2 7 8 13 12 19 25 24
The elements of tree in serialized form : 28 22 2 -1 -1 -1 7 -1 -1 -1 -1 8 13 -1 -1 -1 -1 -1 12 19 -1 -1 -1 25 -1 -1 -1 24 -1 -1 -1  
The elements of tree in deserialized form :  28 22 2 7 8 13 12 19 25 24