我正在寫一個函數,使用結構和指針來計算高度平衡樹的葉節點。該函數需要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--;
}
}
}
它看起來像你已經採取了迭代版本,並試圖重新排列它爲遞歸版本。這通常不起作用。扔掉你的循環,並重新開始只使用遞歸。 – molbdnilo