Visualizzazione dei risultati da 1 a 3 su 3
  1. #1

    c++ procedura su alberi

    salve, ho questa procedura che mi stampa i dati di un albero ordinato in maniera ordinata crescente...

    void InOrderCD(Tnodo A) {
    if (A!=NULL) {

    InOrderCD(A->left);
    cout<<A->key<<endl;
    InOrderCD(A->right);

    }
    }

    ora io dovrei effettuare la stampa sia in maniera crescente che decrescente...
    come posso ottimizzare questa procedura ed effettuare questa stampa sfruttanto la chiamata di PUSH E POP ?

    grazie

  2. #2
    nessuno aiutino?

  3. #3
    Ciao wgd,

    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;
    			}
    		}
    	}
    }
    La prima funzione utilizza uno stack per l'attraversamento dell'albero in ordine crescente. La seconda, ReverseInOrder, è simmetrica alla prima.

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.