okay grazie mille per le risposte e per i chiarimenti...io ho provato ad implementare questo algoritmo di insersione...ma ci deve essere qualcosa che non va...perchè inserendo una sequenza di numeri che leggo da file, e stampando con l'algoritmo "inOrder" stampa solo l'ultimo numero che legge da file...non sono riuscito a capire il problema...se qualcono mi sa dare una dritta...grazie mille...
input da file : 10 6 10 4 5 4
output: 4
posto qua il codice:
codice:#include <stdio.h> #include <stdlib.h> typedef struct arbero { int val; struct arbero *left; struct arbero *right; }tree; tree* NewE ( void ); tree* insertion ( tree* ptr, int v ); void print_in_order ( tree* ptr ); int main () { tree* root; int v; FILE *aptr; root = NULL; aptr = fopen("valori.txt","r"); while ( fscanf(aptr,"%d", &v) != EOF ) { root = insertion ( root, v ); } fclose(aptr); print_in_order ( root ); printf ("\n"); system("pause"); return(1); } tree* insertion ( tree* ptr, int v ) { if ( ptr == NULL ) { ptr = NewE ( ); ptr->val = v; ptr->left = NULL; ptr->right = NULL; } else { if ( v < ptr->val ) { ptr = insertion ( ptr->left, v ); } else if ( v > ptr->val ) { ptr = insertion ( ptr->right, v ); } else { printf ("Dato duplicato\n"); } } return ( ptr ); } void print_in_order ( tree* ptr ) { if ( ptr != NULL ) { print_in_order ( ptr->left ); printf ("%3d", ptr->val); print_in_order ( ptr->right ); } } tree* NewE ( void ) { tree* p; p = (tree*)malloc(sizeof(tree)); if ( p == NULL ) { printf ("Errore allocazione!\n"); system("pause"); exit(1); } return (p); }

Rispondi quotando