fork download
  1.  
  2. #include <stdlib.h>
  3. #include <stdio.h>
  4. #include <ctype.h>
  5.  
  6. #define fatal(...) exit((printf("Fatal" __VA_ARGS__), puts(""), 1))
  7.  
  8. typedef struct Node Node;
  9.  
  10. struct Node {
  11. int data;
  12. Node *left;
  13. Node *right;
  14. };
  15.  
  16. int is_leaf(int c)
  17. {
  18. return !isalpha(c); // non-alphas are leaves
  19. }
  20.  
  21. Node *make_node(int data)
  22. {
  23. Node *node = calloc(1, sizeof(*node));
  24.  
  25. node->data = data;
  26.  
  27. return node;
  28. }
  29.  
  30. void destroy_node(Node *node)
  31. {
  32. if (node) {
  33. destroy_node(node->left);
  34. destroy_node(node->right);
  35. free(node);
  36. }
  37. }
  38.  
  39. void print(const Node *node, int level)
  40. {
  41. if (node) {
  42. print(node->left, level + 1);
  43. printf("%*c\n", 4*level + 1, node->data);
  44. print(node->right, level + 1);
  45. }
  46. }
  47.  
  48. enum {
  49. MAX = 20
  50. };
  51.  
  52. int main(void)
  53. {
  54. int post[] = {'7', '6', '3', 'A', 'B', 0};
  55. int *p = post;
  56.  
  57. Node *head = NULL;
  58. Node *stack[MAX];
  59. int nstack = 0;
  60.  
  61. while (*p) {
  62. int data = *p++;
  63.  
  64. if (is_leaf(data)) {
  65. if (nstack == MAX) fatal("Stack overflow!");
  66.  
  67. stack[nstack++] = make_node(data);
  68. } else {
  69. if (nstack < 2) fatal("Stack underflow!");
  70.  
  71. Node *node = make_node(data);
  72.  
  73. node->right = stack[--nstack];
  74. node->left = stack[--nstack];
  75. stack[nstack++] = node;
  76. }
  77. }
  78.  
  79. if (nstack != 1) fatal("Ill-formed full binary tree!");
  80.  
  81. head = stack[0];
  82.  
  83. print(head, 0);
  84. destroy_node(head);
  85.  
  86. return 0;
  87. }
  88.  
Success #stdin #stdout 0s 4540KB
stdin
Standard input is empty
stdout
    7
B
        6
    A
        3