nelson33

Untitled

Oct 12th, 2023
268
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.34 KB | Source Code | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <math.h>
  4. #include <limits.h>
  5.  
  6. typedef struct _Node {
  7. int height;
  8. struct _Node* l, *r;
  9. }Node;
  10.  
  11. Node* createNode (int h) {
  12. Node* newNode = (Node*) malloc (sizeof(Node));
  13. newNode->height = h;
  14. newNode->l = NULL;
  15. newNode->r = NULL;
  16. }
  17.  
  18. Node* constructTree (int* arr, int N, int index) {
  19. if (index >= N)
  20. return NULL;
  21.  
  22. Node* newNode = createNode(arr[index]);
  23. if (newNode == NULL)
  24. return NULL;
  25.  
  26. newNode->l = constructTree(arr, N, index + 1);
  27. newNode->r = constructTree(arr, N, index + 2);
  28.  
  29. return newNode;
  30. }
  31.  
  32. void dfs (Node* root, int* min, int pre) {
  33. if (root == NULL) return;
  34. if (root->l == NULL && root->r == NULL) {
  35. if (pre < *min)
  36. *min = pre;
  37. }
  38. if (root->l != NULL)
  39. dfs (root->l, min, pre + abs(root->height - root->l->height));
  40. if (root->r != NULL)
  41. dfs (root->r, min, pre + abs(root->height - root->r->height));
  42.  
  43. return;
  44. }
  45.  
  46. int main() {
  47. int N;
  48. scanf("%d", &N);
  49.  
  50. int arr[N];
  51. for (int i = 0; i < N; i++)
  52. scanf("%d", &arr[i]);
  53.  
  54. Node* root = constructTree (arr, N, 0);
  55.  
  56. int value = INT_MAX;
  57. int *min = &value;
  58. int prefix = 0;
  59.  
  60. dfs (root, min, prefix);
  61. printf("%d\n", *min);
  62.  
  63. return 0;
  64. }
Advertisement
Add Comment
Please, Sign In to add comment