Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- typedef struct cvor {
- int broj;
- struct cvor *levo;
- struct cvor *desno;
- }Cvor;
- Cvor *napravi_cvor (int broj){
- Cvor *novi=(Cvor*)malloc(sizeof(Cvor));
- if(novi==NULL)
- return NULL;
- novi->broj=broj;
- novi->levo=NULL;
- novi->desno=NULL;
- return novi;
- }
- void obrisi_stablo(Cvor **adresa_korena){
- if(*adresa_korena==NULL)
- return ;
- obrisi_stablo(&(*adresa_korena)->levo);
- obrisi_stablo(&(*adresa_korena)->desno);
- free(*adresa_korena);
- *adresa_korena=NULL;
- }
- int dodaj_u_stablo(Cvor **adresa_korena, int broj){
- if(*adresa_korena==NULL){
- Cvor *novi=napravi_cvor(broj);
- if(novi==NULL)
- return 1;
- *adresa_korena=novi;
- return 0;
- }
- if(broj<(*adresa_korena)->broj)
- return dodaj_u_stablo(&(*adresa_korena)->levo, broj);
- else
- return dodaj_u_stablo(&(*adresa_korena)->desno, broj);
- }
- void ispisi_stablo(Cvor *koren){
- if(koren==NULL)
- return;
- ispisi_stablo(koren->levo);
- printf("%d ", koren->broj);
- ispisi_stablo(koren->desno);
- }
- int sumiraj_n(Cvor *koren, int n){
- if(koren==NULL)
- return 0;
- if(n==0)
- return koren->broj;
- return sumiraj_n(koren->levo, n-1)+sumiraj_n(koren->desno, n-1);
- }
- int main (){
- int n;
- Cvor *koren=NULL;
- int broj;
- int resenje;
- printf("unesite broj n:\n");
- scanf("%d", &n);
- if(n<0){
- printf("Greska.\n");
- exit(EXIT_FAILURE);
- }
- while(1){
- scanf("%d", &broj);
- if(broj==0)
- break;
- if(dodaj_u_stablo(&koren,broj)){
- printf("-1\n");
- obrisi_stablo(&koren);
- exit(EXIT_FAILURE);
- }
- }
- resenje=sumiraj_n(koren, n);
- printf("Suma je %d", resenje);
- printf("\n");
- ispisi_stablo(koren);
- obrisi_stablo(&koren);
- exit(EXIT_SUCCESS);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement