首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

c语言,递归函数,计算树的高度和节点的数目解决方法

2012-04-09 
c语言,递归函数,计算树的高度和节点的数目我自己编写的程序,又找不到错的地方,运行一下的时候就是只能输入

c语言,递归函数,计算树的高度和节点的数目
我自己编写的程序,又找不到错的地方,运行一下的时候就是只能输入n和h的值,然后程序就崩了,计算不出要计算的高度和节点的数目,错在哪里了啊。。。麻烦各位了,先谢过哈

#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;
}


[解决办法]
楼主还是慢慢调试吧,这样进步更快。一楼正解。楼主的野指针直接使用肯定是不对的。最起码要给他分配各内存吧,用malloc或者new,或者用entity直接声明

热点排行