apposto...ho controllato il codice al compilatore...ho scritto un pò tutto...e dovrebbe funzionare così:
codice:
#include <stdlib.h>
#include <stdio.h>
typedef struct albero_binario {
int val;
struct albero_binario *left;
struct albero_binario *right;
} bst;
bst* insert ( bst* top, int val );
void printLevel( bst* a, int currentLevel, int level, int* somma);
int main ()
{
bst* head;
int val;
int somma=0;
head = NULL;
while ( val != 0 ) {
printf ("Inserire valore (0-termina): ");
scanf ("%d", &val);
if ( val != 0 )
head = insert ( head, val );
}
printLevel ( head, 0, 1, &somma );
printf ("La somma del livello e: %d\n", somma);
system ("pause");
return 1;
}
bst* insert ( bst* top, int val )
{
bst *pNew;
if ( top == NULL ) {
pNew = (bst*)malloc(sizeof(struct albero_binario));
pNew->val = val;
pNew->left = NULL;
pNew->right = NULL;
top = pNew;
}
else {
if ( val > top->val ) {
top->right = insert ( top->right, val );
}
else top->left = insert ( top->left, val );
}
return top;
}
void printLevel( bst* a, int currentLevel, int level, int* somma)
{
if(a == NULL || currentLevel > level)
return;
if(currentLevel == level) {
(*somma) += a->val;
}
printLevel(a->left, currentLevel+1, level, somma);
printLevel(a->right, currentLevel + 1, level, somma);
return;
}
fatemi sapere ancora se c'è qualcosa che non quadra. e scusatemi per l'errore di prima, ma è dovuto un pò alla distrazione di aver scritto il codice senza provarlo!