c语言,递归函数,计算树的高度和节点的数目
#include <stdio.h>typedef struct noeud {
int value;
int height;
struct noeud * pere;
int nbfils ;
struct noeud ** fils;
int rang;
} t_noeud;
t_noeud *cree_racine(void){
t_noeud *racine;
racine-> value=0.;
racine-> height=0;
racine-> nbfils=0;
racine-> fils=NULL;
racine-> pere=NULL;
racine-> rang=0;
return racine;
}
t_noeud *cree_enfants(t_noeud *individu, int const n){
t_noeud * courant ;
int i;
individu->nbfils= n ;
individu->fils = malloc(n*sizeof(t_noeud*));
for (i = 0; i < n; i++)
{
courant = malloc(sizeof(t_noeud));
individu->fils[i] = courant;
courant->rang=i;
courant->height=individu->height+1;
courant->value=0;
courant->pere=individu;
courant->nbfils=0;
courant->fils=NULL;
}
return ;
}
int hauteur (t_noeud *racine) {
int h=0,hfils=0;
int i;
if (racine->nbfils=0)return 0;
else {for (i=0;i<racine->nbfils;i++){hfils=hauteur(racine->fils[i]);if(h<hfils)h=hfils;};}
return h+1;
}
int taille (t_noeud *racine) {
int s=0,sfils=0;
int i;
if (racine->nbfils=0)return 1;
else {for (i=0;i<racine->nbfils;i++){sfils=taille(racine->fils[i]);s+=sfils;};}
return s+1;
}
void arbre_n_aire(t_noeud *racine,int n,int h){
int i;
racine=cree_racine();
if (h>0){cree_enfants(racine,n);
arbre_n_aire(racine->fils[i],n,h);}
return;
}
int main(){
t_noeud *racine;
int n,h;
printf("please give the number of children you want n=");
scanf ("%d",&n);
printf("\nplease give the height you want h=");
scanf ("%d",&h);
arbre_n_aire(racine,n,h);
printf("the whole number of children is %d\n",taille (racine));
printf("the height of the tree is %d\n",hauteur (racine));
return 0;
}