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
/
esempi
/
Tipi_di_dato
/
Alberi
/
trees.c
< prev
next >
Wrap
C/C++ Source or Header
|
1997-05-15
|
3KB
|
115 lines
#include<stdio.h>
#include "trees.h"
#include "queue.h"
tree emptytree(void) { return NULL;}
int is_empty_tree(tree T) { return (T==emptytree());}
int is_leaf(tree T)
{
return (T!=emptytree() &&
T->left==emptytree() &&
T->right==emptytree());
}
tree maketree(int root, tree left, tree right)
{
tree T;
T=(tree)malloc(sizeof(struct node));
T->root=root;
T->left=left;
T->right=right;
return T;
}
int root(tree T) { return T->root; }
int length(tree T)
{
int N,M;
if (is_empty_tree(T)) return 0;
else
{
N=length(T->left);
M=length(T->right);
return (N>M?N+1:M+1);
}
}
int append(int Leaf,tree T,tree T1,tree T2)
/* aggiunge alla prima foglia piu' a sx */
{
if (is_empty_tree(T)) return 0;
if (is_leaf(T) && root(T)==Leaf)
{
T->left=T1;
T->right=T2;
return 1;
}
else return
(append(Leaf,T->left,T1,T2) || append(Leaf,T->right,T1,T2));
}
void copy(tree T,tree *C)
{
tree L,R;
if (is_empty_tree(T)) (*C)=emptytree();
else
{
copy(T->left,&L);
copy(T->right,&R);
(*C)=maketree(root(T),L,R);
}
}
void dfs(tree T)
{
if (!is_empty_tree(T))
{
dfs(T->left);
printf(" %d",root(T));
dfs(T->right);
}
}
void bfs(tree T)
{
queue Q;
/* le code hanno come elementi un puntatore a nodo (tree),
il livello del nodo considerato e l'etichetta del padre
Qui mi interessa stamapare l'albero a livelli (cioe' andare a capo
alla fine di ogni livello) e' per questo che memorizzo il livello
dei nodi nella coda. Memorizzare anche il padre puo' essere utile leggere
poi il risultato in stampa.
*/
int level=0;
int level1,father;
empty_queue(&Q);
enqueue(T,level,0,&Q); /* T e' il puntatore alla radice! */
printf("\n");
while (!is_empty_queue(&Q))
{
T=(tree)dequeue(&Q,&level1,&father); /* seleziono il prossimo nodo da visitare cioe` T */
if (level1>level) /* se e' ad un livello inf. a quello corr. vado a capo */
{
printf("\n");
level=level1;
}
if (!is_empty_tree(T)) /* visito il nodo e salvo nella coda i puntatori ai figli */
{
printf(" %d(%d,%d)",T->root,father,level);
enqueue(T->left,level+1,T->root,&Q);
enqueue(T->right,level+1,T->root,&Q);
}
}
destroy(&Q);
}