簡體   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