2015-11-02 93 views
-1

我正在寫一個函數,使用結構和指針來計算高度平衡樹的葉節點。該函數需要3個參數:樹,指向數組的指針和樹的最大深度。陣列的長度是最大深度。當函數被調用時,數組被初始化爲零。該函數遞歸地跟隨樹結構, 跟蹤深度,並在右邊的計數器到達葉子時遞增。該函數不跟隨任何比maxdepth更深的指針。如果沒有深度大於maxdepth的葉子,函數返回0,如果有一些指向深度的指針,則返回1。我的代碼有什麼問題。謝謝。計數高度平衡樹的葉節點的計數函數

typedef int object; 
typedef int key; 
typedef struct tree_struct { key key; 
    struct tree_struct *left; 
    struct tree_struct *right; 
    int   height; 
} tree_n; 


int count_d (tree_n *tr, int *count, int mdepth) 
{ 
    tree_n *tmp; 
    int i; 
    if (*(count + 0) == NULL){ 
     for (i =0; i<mdepth; i++){ 
     *(count + i) = 0; 
     } 
    } 

    while (medepth != 0) 
    { 
     if (tr == NULL) return; 
     else if (tree-> left == NULL || tree->right == NULL){ 
     return (0); 
     } 

     else { 
     tmp = tr; 
     *(count + 0) = 1; 
     int c = 1; 
     while(tmp->left != NULL && tmp->right != NULL){ 
      if(tmp-> left){ 
       *(count + c) = 2*c; 
       tmp = tmp->left; 
       return count_d(tmp, count , mdepth); 
      } 
      else if(tmp->right){ 
       *(count + c + 1) = 2*c + 1; 
       tmp = tmp->right; 
       return count_d(tmp,count, mdepth); 

      } 
      c++; 
      mpth--; 
     } 
     } 
    } 
+0

它看起來像你已經採取了迭代版本,並試圖重新排列它爲遞歸版本。這通常不起作用。扔掉你的循環,並重新開始只使用遞歸。 – molbdnilo

回答

2

什麼是錯我的代碼

有一件事我注意到的是,你缺少的遞歸調用return

return count_d(tmp, count , mdepth); 
// ^^^ Missing 

有兩個這樣的調用。確保將return添加到他們兩個。

聲明:修復此問題可能無法解決您的所有問題。

+0

@R Sahu,謝謝那部分正在照顧;你能發現需要完成的其他問題或改進嗎? – yanker

+0

@ yanker,我無法按照你的功能邏輯。 –

+0

好吧,我試圖執行上述指令的狀態。因此,將數組初始化爲零可以完美地工作。但我認爲計數並不奏效,因爲如果我插入10個節點,我會得到:[1 2 0 0 0 0 0 0 0 0 0]而不是[1 2 3 4 5 6 7 8 9 10] – yanker