Buonasera a tutti, devo creare un albero binario ordinato in linguaggio C tramite funzione ricorsiva e poi creare una funzione di stampa per poterlo stampare in ordine crescente.
Son arrivato a tale programmazione ma sembrerebbe entrare in loop all'interno della funzione stampa. Temo che ci sia un problema nella creazione vera e propria dell'albero ordinato. Riuscite ad aiutarmi?
#include <stdio.h>
#include <stdlib.h>
typedef struct nodo {
int elem;
struct nodo *left;
struct nodo *right;
} Nodo;
typedef Nodo * tree;
tree ins_ord(int a,tree);
void stampa(tree t);
int main () {
tree t;
int i;
int v[]={8,4,12,2,6,10,14,1,3,5,7,9,11,13,15,0};
for (i=0;i!=0;i++)
t=ins_ord(v,t);
stampa(t);
return 0;
}
tree ins_ord(int a,tree t) {
if (t==NULL) {
t=malloc(sizeof(Nodo));
t->right=NULL;
t->left=NULL;
t->elem=a;
return t;}
if (a>t->elem) {
t->right=ins_ord(a,t->right);
return t;}
else {t->left=ins_ord(a,t->left);
return t;}
}
void stampa (tree t) {
if (t!=NULL) {
stampa(t->left);
printf("%d",t->elem);
stampa(t->right);
}
}
Son arrivato a tale programmazione ma sembrerebbe entrare in loop all'interno della funzione stampa. Temo che ci sia un problema nella creazione vera e propria dell'albero ordinato. Riuscite ad aiutarmi?
#include <stdio.h>
#include <stdlib.h>
typedef struct nodo {
int elem;
struct nodo *left;
struct nodo *right;
} Nodo;
typedef Nodo * tree;
tree ins_ord(int a,tree);
void stampa(tree t);
int main () {
tree t;
int i;
int v[]={8,4,12,2,6,10,14,1,3,5,7,9,11,13,15,0};
for (i=0;i!=0;i++)
t=ins_ord(v,t);
stampa(t);
return 0;
}
tree ins_ord(int a,tree t) {
if (t==NULL) {
t=malloc(sizeof(Nodo));
t->right=NULL;
t->left=NULL;
t->elem=a;
return t;}
if (a>t->elem) {
t->right=ins_ord(a,t->right);
return t;}
else {t->left=ins_ord(a,t->left);
return t;}
}
void stampa (tree t) {
if (t!=NULL) {
stampa(t->left);
printf("%d",t->elem);
stampa(t->right);
}
}