fork download
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. struct tree
  4. {
  5. struct tree* left;
  6. struct tree* right;
  7. int x;
  8. };
  9. struct tree* makenode(int x)
  10. {
  11. struct tree * root = malloc(sizeof(struct tree));
  12. root -> x = x;
  13. root -> left = root -> right = NULL;
  14. return root;
  15. }
  16.  
  17. struct tree* makeBST(int *post, int start, int n, int inorder){
  18. if(n <= 0)
  19. return NULL;
  20. int pivot = post[start + n -1];
  21. struct tree * root = makenode(pivot);
  22. root -> left = makeBST(post, start, pivot-1 - inorder, inorder );
  23. root -> right = makeBST(post, pivot - inorder - 1, n - (pivot - inorder), pivot);
  24. return root;
  25. }
  26. void preorder(struct tree* node)
  27. {
  28. if(node == NULL)
  29. return;
  30. printf("%d ", node->x);
  31. preorder(node->left);
  32. preorder(node->right);
  33. }
  34. void printdot(struct tree* node, FILE * f)
  35. {
  36. if(node == NULL)
  37. return;
  38. if(node-> left != NULL)
  39. {
  40. fprintf(f, "%d -- %d;\n", node->x, node->left->x);
  41. }
  42. if(node-> right != NULL)
  43. {
  44. fprintf(f, "%d -- %d;\n", node->x, node->right->x);
  45. }
  46. printdot(node->left, f);
  47. printdot(node->right, f);
  48. }
  49.  
  50. int main(){
  51. int i, n, *a;
  52. printf("Enter n: ");
  53. scanf("%d", &n);
  54. a = malloc(n * sizeof(int));
  55. printf ("Enter post order traversal: ");
  56. for(i = 0; i < n; i++)
  57. {
  58. scanf("%d", &a[i]);
  59. }
  60. struct tree * tree = makeBST(a, 0, n, 0);
  61. printf("Pre order traversal is : ");
  62. preorder(tree);
  63. printf("\n");
  64. FILE * f = fopen("tree.dot", "w");
  65. fprintf(f, "graph tree { \n");
  66. printdot(tree, f);
  67. fprintf(f, "}\n");
  68. fclose(f);
  69. return 0;
  70. }
  71.  
Internal error #stdin #stdout 0s 0KB
stdin
5
11
10
9
6
7
stdout
Standard output is empty