The_Law

Untitled

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