Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 2derevo
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- struct tree{
- int key;
- struct tree *left, *right, *parent;
- };
- int cmp(const void *x1, const void *x2){
- return (*(int*)x1 - *(int*)x2);
- }
- struct tree *distrib(int *a, int n){
- if (n <= 0) return NULL;
- static int KEK;
- struct tree *non;
- non = malloc(sizeof(struct tree));
- if (!KEK) {
- qsort(a, n, sizeof(int), cmp);
- KEK = 1;
- non -> parent = NULL;
- }
- if (n == 1) {
- printf("%d \n", a[0]);
- non -> left = non -> right = NULL;
- non -> key = a[0];
- return non;
- }
- int t = n / 2 - (1 - n&1);
- non -> key = a[t];
- non -> left = distrib(a, t);
- non -> right = distrib(a + t + 1, n - t - 1);
- if (non -> left)
- non -> left -> parent = non;
- if (non -> right)
- non -> right -> parent = non;
- return non;
- };
- void print(struct tree * t) {
- if (!t) return;
- print(t->left);
- printf("(%d)\n", t -> key);
- print(t->right);
- }
- int main(void){
- int n;
- scanf("%d", &n);
- int a[n];
- for (int i = 0; i < n; ++i)
- scanf("%d", &a[i]);
- print( distrib(a, n) );
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment