Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jsf-2/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
打印二叉树asc/desc限制C中的节点数_C_Binary Tree_Nodes_Limit_Ordered Tree - Fatal编程技术网

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

打印二叉树asc/desc限制C中的节点数,c,binary-tree,nodes,limit,ordered-tree,C,Binary Tree,Nodes,Limit,Ordered Tree,我在限制从二叉树打印的节点数方面遇到了一些问题。我有当前代码: abp.h abp.c BTree已经像每个BTree一样排序,左下,右上。为了按asc顺序打印,我使用了函数centralEsquerda(),为了按desc顺序打印,我使用了只反转递归调用的centraldirita(),它首先调用右节点(a->dir) 因此,使用上面的代码,将打印1、2、3、4、5、6、7、8、9、10、11、12、13、14、15、16、17、18、19、20,并且我希望使用centralEsquerda(

我在限制从二叉树打印的节点数方面遇到了一些问题。我有当前代码:

abp.h

abp.c

BTree已经像每个BTree一样排序,左下,右上。为了按asc顺序打印,我使用了函数
centralEsquerda()
,为了按desc顺序打印,我使用了只反转递归调用的
centraldirita()
,它首先调用右节点(
a->dir

因此,使用上面的代码,将打印1、2、3、4、5、6、7、8、9、10、11、12、13、14、15、16、17、18、19、20,并且我希望使用
centralEsquerda(节点,5)
,它应该打印1、2、3、4、5

有什么想法吗? ps.无法使用队列/列表

[更新]

用下面的代码解决了,但我不满意

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