[英]C - binary tree: can't return correct number of pruned nodes
我需要修剪超過一定級別l的二叉樹,並且需要返回修剪的節點數。
這是我得到的:
#include "abin.h"
int freeAB (ABin a) {
int count = 0;
if(a == NULL) return count;
count = count + freeAB(a->esq);
count = count + freeAB(a->dir);
free(a);
count++;
return count;
}
int pruneAB (ABin *a, int l) {
int count = 0;
if(l == 0){
count = count + freeAB((*a)->esq);
count = count + freeAB((*a)->dir);
(*a) = NULL;
}
else{
count = count + pruneAB(&((*a)->esq), l-1);
count = count + pruneAB(&((*a)->dir), l-1);
}
return count;
}
ABIN.H:
#include <stdio.h>
#include <stdlib.h>
typedef struct lligada {
int valor;
struct lligada *prox;
} *LInt;
typedef struct nodo {
int valor;
struct nodo *esq, *dir;
} *ABin;
int pruneAB (ABin *a, int l);
這是我應該得到和得到的結果的輸出:
Input: (depth=2)
8
4 12
2 6 10 14
1 3 5 7 9 11 13 15
Output:
[expected] res=12
8
4 12
[obtained] res=8
8
4 12
0/10 correct answers
有趣的是,如果我創建類似int r = 0的東西; 並做r ++; 每當if(l == 0)語句為true,然后執行print語句時,它將打印r 4次。
如果我在最終計數中加4,我會得到正確的答案。 我假設我應該加法計算if(l == 0)為真的次數。
(我做不到。如果我計算++,我會遇到細分錯誤)
你會怎么做? 謝謝。
int pruneAB (ABin *a, int l) {
int count = 0;
if (!*a) return 0;
if (l < 0) return count;
if(l == 0){
count = freeAB(*a);
(*a) = NULL;
}
else{
count = count + pruneAB(&((*a)->esq), l-1);
count = count + pruneAB(&((*a)->dir), l-1);
}
return count;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.