Ciao wgd,
La prima funzione utilizza uno stack per l'attraversamento dell'albero in ordine crescente. La seconda, ReverseInOrder, è simmetrica alla prima.codice:typedef struct tagTree { int data; struct tagTree *left; struct tagTree *right; } Tree; /* Stampa l'albero in ordine crescente */ void InOrder(Tree * p) { Tree *temp; Tree *stack[MAX_STACK]; int top; top = -1; if ( !p ) return; temp = p; while ( 1 ) { if ( temp != NULL ) { if ( top < MAX_STACK ) { stack[++top] = temp; // Push temp = temp->left; } else { printf("Errore: lo stack e' pieno.\n"); return; } } else { if ( top >= 0 ) { temp = stack[top--]; // Pop printf("%d\n", temp->data); temp = temp->right; } else { break; } } } } /* Stampa l'albero in ordine decrescente */ void ReverseInOrder(Tree * p) { Tree *temp; Tree *stack[MAX_STACK]; int top; top = -1; if ( !p ) return; temp = p; while ( 1 ) { if ( temp != NULL ) { if ( top < MAX_STACK ) // Push { stack[++top] = temp; temp = temp->right; } else { printf("Errore: lo stack e' pieno.\n"); return; } } else { if ( top >= 0 ) { temp = stack[top--]; // Pop printf("%d\n", temp->data); temp = temp->left; } else { break; } } } }

Rispondi quotando