9Y8y

Untitled

Feb 28th, 2022
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.66 KB | None | 0 0
  1. /******************************************************************************
  2.  
  3. Online C Compiler.
  4. Code, Compile, Run and Debug C program online.
  5. Write your code in this editor and press "Run" button to compile and execute it.
  6.  
  7. *******************************************************************************/
  8.  
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11.  
  12. struct _node {
  13. int id;
  14. int p;
  15. int sibling;
  16. int degree;
  17. int depth;
  18. int height;
  19. int type;
  20. struct _node *left;
  21. struct _node *right;
  22. };
  23.  
  24. typedef struct _node node;
  25. int height(node*);
  26. int max(int, int);
  27.  
  28. int main()
  29. {
  30. int n, i, d, PP, id, l, r;
  31. scanf("%d", &n);
  32. node *T = (node*)malloc(n*sizeof(node));
  33.  
  34. /* initialize parents & sibling */
  35. for (i=0; i<n; i++) {
  36. T[i].p = -1;
  37. T[i].sibling = -1;
  38. }
  39.  
  40. /* input node info */
  41. for (i=0; i<n; i++) {
  42. scanf("%d", &id);
  43. scanf("%d%d", &l, &r);
  44. T[id].id = id;
  45. T[l].p = T[r].p = id;
  46. T[l].sibling = r;
  47. T[r].sibling = l;
  48. if (l!=-1) {
  49. T[id].left = &(T[l]);
  50. T[id].right = &(T[r]);
  51. T[id].degree = 2;
  52. }
  53. else {
  54. T[id].left = NULL;
  55. T[id].right = NULL;
  56. T[id].degree = 0;
  57. }
  58.  
  59.  
  60. }
  61.  
  62. /* judge type */
  63. for (i=0; i<n; i++) {
  64. if (T[i].p == -1) T[i].type = 0;
  65. else if (T[i].degree != 0) T[i].type = 1;
  66. else T[i].type = 2;
  67. }
  68.  
  69.  
  70. /* calc depth */
  71. for (i=0; i<n; i++) {
  72. d = 0;
  73. PP = i;
  74. while(1) {
  75. if (T[PP].p == -1) {
  76. T[i].depth = d;
  77. break;
  78. }
  79. else {
  80. PP = T[PP].p;
  81. d++;
  82. }
  83. }
  84. }
  85.  
  86. /* calc height */
  87. for (i=0; i<n; i++) {
  88. T[i].height = height(&T[i]) - 1;
  89. }
  90.  
  91. /* print */
  92. for (i=0; i<n; i++) {
  93. printf("node %d: ", i);
  94. printf("parent = %d, ", T[i].p);
  95. printf("sibling = %d, ", T[i].sibling);
  96. printf("degree = %d, ", T[i].degree);
  97. printf("depth = %d, ", T[i].depth);
  98. printf("height = %d, ", T[i].height);
  99. if (T[i].type == 0) printf("root");
  100. else if (T[i].type == 1) printf("internal node");
  101. else printf("leaf");
  102. printf("\n");
  103. }
  104.  
  105. free(T);
  106.  
  107. return 0;
  108. }
  109.  
  110.  
  111.  
  112. int height(node* root) {
  113. if (root == NULL) return 0;
  114. return 1 + max(height(root->left), height(root->right));
  115. }
  116.  
  117. int max(int a, int b) {
  118. if (a > b) return a;
  119. return b;
  120. }
  121.  
  122.  
Advertisement
Add Comment
Please, Sign In to add comment