繁体   English   中英

在C中打印二叉树asc / desc限制节点数

[英]Print binary tree asc/desc limiting number of nodes in C

我在限制从二叉树打印的节点数方面遇到麻烦。 我有当前代码:

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()centralDireita()反转了递归调用,它首先调用了正确的节点( a->dir )。

因此,使用上述代码,将分别打印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);
    }
}

我讨厌我的第一个答案是未经测试的代码。 请认为它是伪代码。 呵呵。 我认为您的解决方案(尽管功能强大)不能令人满意,因为它不像您的原始递归树遍历代码那样优雅。 我们的递归爱好者往往对这些事情着迷。 这是一个片段(未经测试),我觉得它更递归:

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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM