2014-03-31 92 views
1

我寫了一個應該使用遞歸來增長'雪花'的方法,它本質上是一棵樹。出於某種原因,在調試時,它只向樹添加一行,不會超過這一行。我認爲它與指針有關,但似乎無法弄清楚它有什麼問題。幫助將非常感激。用指針遞歸-C

int growth(Snowflake * root, Snowflake * parent, Ray * ray){ 
    printf("*\n"); 
    printf("%f\n", root->ray->starting_point); 
    printf("%f\n", ray->angle); 
    if (root->middle != NULL){ 
     printf("Found middle! \n"); 
     growth(root->middle, root, ray); 
    } 
    else if (root->right != NULL){ 
     printf("Found off center!\n"); 
     growth(root->right, root, ray); 
     printf("Found off middle!\n"); 
     growth(root->left, root, ray); 
    } 
    else{ 
     if (parent == NULL){ 
      printf("MY PARENTS ARE DEAD!\n"); 
      parent = root; 
      //root = &parent; 
     } 
     printf("Starting Again!\n"); 
     Snowflake * add = malloc(sizeof(Snowflake)); 
     add->parent = parent; 
     add->middle = NULL; 
     add->right = NULL; 
     add->left = NULL; 
     add->ray = ray; 
     add->ray->starting_point = add->parent->ray->end_point; 
     add->ray->end_point = add->ray->starting_point + 1; 
     printf("%f\n",add->ray->starting_point); 
     printf("%f\n",add->ray->end_point); 
     if (add->ray->angle == 0){ 
      add->parent->middle = add; 
     } 
     else{ 
      add->parent->right = add; 
      add->parent->left = add; 
     } 
     return 1; 
    } 
} 
+4

您是否嘗試過使用調試器? – dutt

+1

請縮進你的代碼,並提供'Snowflake'和'Ray'類型的定義。 – ajay

+0

@達特,你有沒有試過看OP的前兩句話? – CiaPan

回答

0

我看到下面的問題與您的代碼:

  1. 我看不出有任何的檢查,以確保root != NULL
  2. 我不知道你是否使用函數的返回值。有三個函數遞歸調用,其中沒有一個返回。我認爲,

    growth(root->middle, root, ray); 
    

    return growth(root->middle, root, ray); 
    
  3. 在此塊來替換,

    else if (root->right != NULL){ 
        printf("Found off center!\n"); 
        growth(root->right, root, ray); 
        printf("Found off middle!\n"); 
        growth(root->left, root, ray); 
    } 
    

    你不檢查root->left是否NULL。也許你想用的是:

    else if (root->right != NULL){ 
        printf("Found off center!\n"); 
        growth(root->right, root, ray); 
    } 
    else if (root->left != NULL){ 
        printf("Found off middle!\n"); 
        growth(root->left, root, ray); 
    } 
    

    如果你想用第二個代碼塊,我想補充的return聲明對夫婦和其更改爲:

    else if (root->right != NULL){ 
        printf("Found off center!\n"); 
        return growth(root->right, root, ray); 
    } 
    else if (root->left != NULL){ 
        printf("Found off middle!\n"); 
        return growth(root->left, root, ray); 
    } 
    
  4. 的代碼

    此塊
    if (parent == NULL){ 
         printf("MY PARENTS ARE DEAD!\n"); 
         parent = root; 
         //root = &parent; 
        } 
    

    如果root == NULL將會出現問題。我不知道你如何確定這種事情沒有發生。

希望這會有所幫助。