The_Law

Untitled

Dec 1st, 2017
207
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.22 KB | None | 0 0
  1. 2derevo
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5.  
  6.  
  7. struct tree{
  8.     int key;
  9.     struct tree *left, *right, *parent;
  10. };
  11.  
  12. int cmp(const void *x1, const void *x2){
  13.     return (*(int*)x1 - *(int*)x2);
  14. }
  15.  
  16. struct tree *distrib(int *a, int n){
  17.     if (n <= 0) return NULL;
  18.     static int KEK;
  19.     struct tree *non;
  20.     non = malloc(sizeof(struct tree));
  21.     if (!KEK) {
  22.         qsort(a, n, sizeof(int), cmp);
  23.         KEK = 1;
  24.         non -> parent = NULL;
  25.     }
  26.  
  27.     if (n == 1) {
  28.         printf("%d \n", a[0]);
  29.         non -> left = non -> right = NULL;
  30.         non -> key = a[0];
  31.         return non;
  32.     }
  33.     int t = n / 2 - (1 - n&1);
  34.     non -> key = a[t];
  35.     non -> left = distrib(a, t);
  36.     non -> right = distrib(a + t + 1, n - t - 1);
  37.     if (non -> left)
  38.         non -> left -> parent = non;
  39.  
  40.     if (non -> right)
  41.         non -> right -> parent = non;
  42.  
  43.     return non;
  44. };
  45.  
  46. void print(struct tree * t) {
  47.     if (!t) return;
  48.     print(t->left);
  49.     printf("(%d)\n", t -> key);
  50.     print(t->right);
  51. }
  52.  
  53. int main(void){
  54.     int n;
  55.     scanf("%d", &n);
  56.     int a[n];
  57.     for (int i = 0; i < n; ++i)
  58.         scanf("%d", &a[i]);
  59.  
  60.     print( distrib(a, n) );
  61.     return 0;
  62. }
Advertisement
Add Comment
Please, Sign In to add comment