我需要修剪超过某个级别的二叉树,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)语句为真,然后执行print语句时,它会打印r 4次。
如果我在最终计数中加4,我会得到正确的答案。我假设我应该添加以计算if(l == 0)为真的次数。
(我不能这样做。如果我算数++,我会得到分段错误)
你会怎么做?感谢。
答案 0 :(得分:1)
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;
}