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
/
parte3.c
< prev
next >
Wrap
C/C++ Source or Header
|
1999-03-11
|
2KB
|
89 lines
/* Esame 14 settembre '98 - parte 3 */
#include <stdio.h>
#include <stdlib.h>
#define MAX 30
typedef struct node *tree;
struct node
{
int el;
tree left,right;
};
static int max(int,int);
void insert(int,tree*);
void print(tree);
int height(tree);
int max(int i, int j)
{
return i>j ? i : j;
}
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);
}
}
int height(tree t)
{
if (t==NULL)
return -1; /* albero vuoto */
else
if (t->left==NULL && t->right==NULL)
return 0; /* foglia */
else
return 1+max(height(t->left),height(t->right)); /* nodo interno */
}
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");
printf("Height: ");
printf("%d\n",height(t));
fclose(fd);
}
else
printf("Error opening file %s\n",fname);
}