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.99
/
parte4.c
< prev
next >
Wrap
C/C++ Source or Header
|
1999-10-10
|
2KB
|
95 lines
/* Esame 20 settembre '99 parte 4 */
#include <stdio.h>
#include <stdlib.h>
#define MAX 30
#define FALSE 0
#define TRUE 1
typedef char bool;
typedef struct node *tree;
struct node
{
int el;
tree left,right;
};
tree empty()
{
return NULL;
}
void insert(int i, tree *t)
{
if (*t==empty()) /* caso base: albero vuoto */
{
*t=(tree) malloc(sizeof(struct node));
(*t)->el=i;
(*t)->left=empty();
(*t)->right=empty();
}
else if (i<(*t)->el) /* passo induttivo, sottoalbero sinistro */
insert(i,&((*t)->left));
else if (i>(*t)->el) /* passo induttivo, sottoalbero destro */
insert(i,&((*t)->right));
/* nota bene: nel caso i==(*t)->el non fa nulla! */
}
void print(tree t)
{
if (t!=NULL) /* se l'albero e` vuoto non stampo nulla */
{
print(t->left);
printf(" %d",t->el);
print(t->right);
}
}
int nodes_number(tree t)
{
if(t==empty())
{
return(0);
}
if((t->left==empty()) && (t->right==NULL))
{
return 1;
}
else
{
return(1+nodes_number(t->left)+nodes_number(t->right));
}
}
int main(void)
{
char fname[MAX];
tree t1=NULL,t2=NULL, 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,&t1);
printf("Tree t1 from file %s: ",fname);
print(t1);
printf("\n");
printf("Number of nodes: ");
i=nodes_number(t1);
printf("%d\n\n",i);
fclose(fd);
}
else
printf("Error opening file %s\n",fname);
}