home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
ftp.disi.unige.it
/
2015-02-11.ftp.disi.unige.it.tar
/
ftp.disi.unige.it
/
pub
/
.person
/
CataniaB
/
teach-act
/
testi-esami
/
labo-9.98
/
parte4.c
< prev
next >
Wrap
C/C++ Source or Header
|
1999-03-11
|
2KB
|
105 lines
/* Esame 14 settembre '98 - parte 4 */
#include <stdio.h>
#include <stdlib.h>
#define MAX 30
typedef struct node *tree;
struct node
{
int el;
tree left,right;
};
void insert(int,tree*);
void print(tree);
void delete(int,tree*);
void insert(int i, tree *t)
{
if (*t==NULL) /* caso base: albero vuoto */
{
*t=(tree) malloc(sizeof(struct node));
(*t)->el=i;
(*t)->left=NULL;
(*t)->right=NULL;
}
else if (i<=(*t)->el) /* passo induttivo, sottoalbero sinistro */
insert(i,&((*t)->left));
else /* passo induttivo, sottoalbero destro (i>(*t)->el) */
insert(i,&((*t)->right));
}
void print(tree t)
{
if (t!=NULL) /* se l'albero e` vuoto non stampa nulla */
{
print(t->left);
printf(" %d",t->el);
print(t->right);
}
}
void delete(int i, tree *t)
{
if (*t!=NULL) /* se l'albero e` vuoto non fa nulla */
if (i<(*t)->el)
delete(i,&((*t)->left));
else
if (i>(*t)->el)
delete(i,&((*t)->right));
else /* i==(*t)->el */
if ((*t)->left==NULL && (*t)->right==NULL) /* foglia */
{
free(*t);
*t=NULL;
}
else
if ((*t)->left==NULL) /* nodo solo con figlio destro */
{
tree aux=*t;
*t=(*t)->right;
free(aux);
}
else
if ((*t)->right==NULL) /* nodo solo con figlio sinistro */
{
tree aux=*t;
*t=(*t)->left;
free(aux);
}
/* nota bene: se il nodo ha 2 figli non fa nulla! */
}
int main(void)
{
char fname[MAX];
tree t=NULL;
FILE *fd=NULL;
int i;
printf("Enter file name: ");
scanf("%s",fname);
if (fd=fopen(fname,"r"))
{
while (fscanf(fd,"%d",&i)==1 && i!=-1)
insert(i,&t);
printf("Tree from file %s: ",fname);
print(t);
printf("\n");
fscanf(fd,"%d",&i);
delete(i,&t);
printf("Tree after delete: ");
print(t);
printf("\n");
fclose(fd);
}
else
printf("Error opening file %s\n",fname);
}