我在限制从二叉树打印的节点数方面遇到了一些麻烦。我有当前的代码:
abp.h
struct TNodoA {
int info;
struct TNodoA *esq;
struct TNodoA *dir;
};
typedef struct TNodoA pNodoA;
void centralEsquerda(pNodoA *a, int lim);
pNodoA* InsereArvore(pNodoA *a, int ch);
abp.c
void centralEsquerda(pNodoA *a, int lim) {
if (a != NULL) {
centralEsquerda(a->esq, lim);
printf("%d, ", a->info);
centralEsquerda(a->dir, lim);
}
}
pNodoA* InsereArvore(pNodoA *a, int ch) {
if (a == NULL) {
a = (pNodoA*) malloc(sizeof (pNodoA));
a->info = ch;
a->esq = NULL;
a->dir = NULL;
return a;
} else
if (ch < a->info)
a->esq = InsereArvore(a->esq, ch);
else if (ch > a->info)
a->dir = InsereArvore(a->dir, ch);
return a;
}
的main.c
int teste() {
int valores[20] = {10, 5, 15, 3, 8, 13, 18, 2, 4, 7, 9, 12, 14, 17, 19, 1, 6, 11, 16, 20};
pNodoA *arv = NULL;
for (int i = 0; i < 20; i++) {
arv = InsereArvore(arv, valores[i]);
}
centralEsquerda(arv, 4);
}
第一个想法是将一些static int x = 0;
放在centralEsquerda()
内并递增,但由于第二次递归调用(centralEsquerda(a->dir, lim)
),它无法正常工作。在测试代码下面:
void centralEsquerda(pNodoA *a, int lim) {
static int x = 0;
if (a != NULL && x < lim) {
x++;
centralEsquerda(a->esq, lim);
printf("%d, ", a->info);
centralEsquerda(a->dir, lim);
}
}
BTree已经按照每个BTree排序,左边较低,右边较大。要以asc顺序打印,我使用函数centralEsquerda()
,并以desc顺序打印我使用centralDireita()
只是反转递归调用,它首先调用正确的节点(a->dir
)。 / p>
因此,使用上面的代码,将打印1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19 ,20,我希望使用centralEsquerda(node, 5)
,它应该打印1,2,3,4,5。
有什么想法吗? PS。不想使用队列/列表
[UPDATE] 的
解决了以下代码,但我并不高兴...
void centralEsquerda(pNodoA *a, int lim) {
static int count = 0;
if (a != NULL) {
centralEsquerda(a->esq, lim);
if (count >= lim)
return;
else
count++;
printf("%d, ", a->info);
centralEsquerda(a->dir, lim);
}
}
答案 0 :(得分:1)
我讨厌我的第一个答案是未经测试的代码。请将其视为伪代码。嘿嘿 我认为你的解决方案(虽然功能齐全)并没有让你高兴,因为它不像原来的递归树遍历代码那么优雅。我们的递归爱好者往往会对这些事情着迷。这是一个片段(未经测试),我发现更多的递归令人愉快:
int centralEsquerda(pNodoA *a, int lim) {
if (a != NULL && lim > 0) {
lim = centralEsquerda(a->esq, lim);
if (lim-- > 0) printf("%d, ", a->info);
lim = centralEsquerda(a->dir, lim);
}
return lim;
}