Advertisement
Guest User

jun_2_2015.c

a guest
Jun 22nd, 2017
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.85 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5.  
  6. typedef struct cvor {
  7.   int broj;
  8.   struct cvor *levo;
  9.   struct cvor *desno;
  10. }Cvor;
  11.  
  12. Cvor *napravi_cvor (int broj){
  13.   Cvor *novi=(Cvor*)malloc(sizeof(Cvor));
  14.   if(novi==NULL)
  15.     return NULL;
  16.   novi->broj=broj;
  17.   novi->levo=NULL;
  18.   novi->desno=NULL;
  19.   return novi;
  20. }
  21.  
  22. void obrisi_stablo(Cvor **adresa_korena){
  23.   if(*adresa_korena==NULL)
  24.     return ;
  25.   obrisi_stablo(&(*adresa_korena)->levo);
  26.   obrisi_stablo(&(*adresa_korena)->desno);
  27.   free(*adresa_korena);
  28.   *adresa_korena=NULL;
  29. }
  30.  
  31. int dodaj_u_stablo(Cvor **adresa_korena, int broj){
  32.  
  33.   if(*adresa_korena==NULL){
  34.     Cvor *novi=napravi_cvor(broj);
  35.     if(novi==NULL)
  36.       return 1;
  37.     *adresa_korena=novi;
  38.     return 0;
  39.   }
  40.   if(broj<(*adresa_korena)->broj)
  41.     return dodaj_u_stablo(&(*adresa_korena)->levo, broj);
  42.   else
  43.     return dodaj_u_stablo(&(*adresa_korena)->desno, broj);
  44.  
  45. }
  46.  
  47. void ispisi_stablo(Cvor *koren){
  48.   if(koren==NULL)
  49.     return;
  50.   ispisi_stablo(koren->levo);
  51.   printf("%d  ", koren->broj);
  52.   ispisi_stablo(koren->desno);
  53. }
  54.  
  55. int sumiraj_n(Cvor *koren, int n){
  56.   if(koren==NULL)
  57.     return 0;
  58.   if(n==0)
  59.     return koren->broj;
  60.   return sumiraj_n(koren->levo, n-1)+sumiraj_n(koren->desno, n-1);
  61. }
  62.  
  63. int main (){
  64.  
  65.   int n;
  66.   Cvor *koren=NULL;
  67.   int broj;
  68.   int resenje;
  69.  
  70.   printf("unesite broj n:\n");
  71.   scanf("%d", &n);
  72.  
  73.   if(n<0){
  74.     printf("Greska.\n");
  75.     exit(EXIT_FAILURE);
  76.   }
  77.  
  78.  
  79.   while(1){
  80.     scanf("%d", &broj);
  81.     if(broj==0)
  82.       break;
  83.     if(dodaj_u_stablo(&koren,broj)){
  84.       printf("-1\n");
  85.       obrisi_stablo(&koren);
  86.       exit(EXIT_FAILURE);
  87.     }
  88.   }
  89.  
  90.   resenje=sumiraj_n(koren, n);
  91.  
  92.  
  93.   printf("Suma je %d", resenje);
  94.  
  95.   printf("\n");
  96.  
  97.   ispisi_stablo(koren);
  98.  
  99.   obrisi_stablo(&koren);
  100.  
  101.   exit(EXIT_SUCCESS);
  102. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement