Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <math.h>
- #include <limits.h>
- typedef struct _Node {
- int height;
- struct _Node* l, *r;
- }Node;
- Node* createNode (int h) {
- Node* newNode = (Node*) malloc (sizeof(Node));
- newNode->height = h;
- newNode->l = NULL;
- newNode->r = NULL;
- }
- Node* constructTree (int* arr, int N, int index) {
- if (index >= N)
- return NULL;
- Node* newNode = createNode(arr[index]);
- if (newNode == NULL)
- return NULL;
- newNode->l = constructTree(arr, N, index + 1);
- newNode->r = constructTree(arr, N, index + 2);
- return newNode;
- }
- void dfs (Node* root, int* min, int pre) {
- if (root == NULL) return;
- if (root->l == NULL && root->r == NULL) {
- if (pre < *min)
- *min = pre;
- }
- if (root->l != NULL)
- dfs (root->l, min, pre + abs(root->height - root->l->height));
- if (root->r != NULL)
- dfs (root->r, min, pre + abs(root->height - root->r->height));
- return;
- }
- int main() {
- int N;
- scanf("%d", &N);
- int arr[N];
- for (int i = 0; i < N; i++)
- scanf("%d", &arr[i]);
- Node* root = constructTree (arr, N, 0);
- int value = INT_MAX;
- int *min = &value;
- int prefix = 0;
- dfs (root, min, prefix);
- printf("%d\n", *min);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment