Ciao, come da titolo ho due dubbi su due funzioni.
Ho creato un albero binario di ricerca..........
Vorrei sapere dove sbaglio nella funzione cerca ed elimina:
Di seguito vi copio pezzi di codice:
Quresta è la dichiarazione della struttura albero:
struct treeNode
{
struct treeNode *sinistroPtr;
int data;
struct treeNode *destroPtr;
struct treeNode *padrePtr;
};
typedef struct treeNode TreeNode;
typedef TreeNode *TreeNodePtr;
void inserzione ( TreeNodePtr *treePtr, int value);
void inOrder( TreeNodePtr treePtr);
int minimo( TreeNodePtr treePtr);
int successore( TreeNodePtr treePtr);
int cerca( TreeNodePtr treePtr, int k);
int elimina( TreeNodePtr treePtr);
int main()
{
int i;
int num;
int item;
TreeNodePtr radicePtr = NULL;
srand ( time( NULL ) );
printf("I numeri inseriti sono:\n");
for (i = 1; i <= 10;i++ )
{
item=rand() % 15;
printf("%3d", item);
inserzione(&radicePtr, item);
}
printf("\n\nLa visita inOrder:\n");
inOrder (radicePtr);
successore(radicePtr);
printf("Inserisci numero da cercare");
scanf("%d", &num);
cerca(radicePtr, num);
system("PAUSE");
return 0;
}
Adesso vi copio il codice delle funzioni che servono x la funzione cerca ed elimina:
int minimo( TreeNodePtr treePtr)
{
while (treePtr->sinistroPtr != NULL)
treePtr = treePtr->sinistroPtr;
return treePtr->data;
}
int successore( TreeNodePtr treePtr)
{
TreeNodePtr trPtr;
int suc;
if (treePtr->destroPtr != NULL)
suc= minimo(treePtr->destroPtr);
else
{
trPtr=treePtr->padrePtr;
while(trPtr!=NULL && treePtr==trPtr->destroPtr)
{
treePtr = trPtr;
trPtr = trPtr->padrePtr;
suc= trPtr->data;
}
}
printf("Il successore :%d\n", suc);
}
FINO A QUI TUTTO VA BENE
int cerca( TreeNodePtr treePtr, int k)
{
int cer;
while(treePtr!=NULL || k!=treePtr->data)
{
if (k<treePtr->data)
{
treePtr=treePtr->sinistroPtr;
}
else
{
treePtr=treePtr->destroPtr;
}
}
cer=treePtr->data;
printf("Il numero ricercato %d",cer);
}
che cosa sto sbagliando?????
int elimina( TreeNodePtr treePtr)
{
TreeNodePtr radicePtr;
TreeNodePtr trbisPtr;
TreeNodePtr trPtr;
if (trbisPtr->sinistroPtr == NULL || trbisPtr->destroPtr == NULL)
{
trPtr=trbisPtr;
}
else
{
trPtr->data=successore(trbisPtr);
}
if (trPtr->sinistroPtr != NULL)
{
treePtr = trPtr->sinistroPtr;
}
else
{
treePtr = trPtr->destroPtr;
}
if (treePtr != NULL)
{
treePtr->padrePtr = trPtr->padrePtr;
}
if ( trPtr->padrePtr == NULL)
radicePtr=treePtr;
else
{
if (trPtr==trPtr->padrePtr->sinistroPtr)
{
trPtr->padrePtr->sinistroPtr=treePtr;
}
else
{
trPtr->padrePtr->destroPtr=treePtr;
}
}
if (trPtr!= trbisPtr)
{
trbisPtr=trPtr;
}
return trPtr->data;
}
oltre a controllare se va bene come faccio a eliminare un valore in input?
------------------------------------------------------------------------------------------
Vi chiedo quindi di dirmi cosa sbaglio secondo voi; non mi chiudete il post perchè è importante per me mi serve per l'università. Grazie