Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/59.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
C 二叉搜索树-高度的迭代检查_C_Stack_Height_Binary Search Tree_Non Recursive - Fatal编程技术网

C 二叉搜索树-高度的迭代检查

C 二叉搜索树-高度的迭代检查,c,stack,height,binary-search-tree,non-recursive,C,Stack,Height,Binary Search Tree,Non Recursive,所以,我有点问题。我知道如何遍历树,是否使用递归,是否使用堆栈。但,我还想跟踪每个叶子的高度,若高度(或深度)小于给定参数,则打印该叶子。下面是我使用堆栈的代码: void PrintLevelIter(struct tNode* tree, int h1){ if(h1==0){ printf("%d ",tree->info); return; } struct sNode *stek = NULL; push(&

所以,我有点问题。我知道如何遍历树,是否使用递归,是否使用堆栈。但,我还想跟踪每个叶子的高度,若高度(或深度)小于给定参数,则打印该叶子。下面是我使用堆栈的代码:

void PrintLevelIter(struct tNode* tree, int h1){
    if(h1==0){
        printf("%d ",tree->info);
        return;
    }
    struct sNode *stek = NULL;
    push(&stek,tree);

    struct tNode* current = tree;


    while(!isEmptyStack(stek)){
        pop(&stek);
        printf("%d ",current->info);
        if(current->left != NULL && current->right != NULL){
            if(Depth(current) < h1){
                push(&stek, current);
            }
            else return;
        }
    }
}
问题是,我的输出只给我根值,其他什么都没有。有人知道我在哪里犯错吗?或错误:)

  • 在循环中,不更改
    current
    的值,
    pop(&stek)
    应该是
    current=pop(&stek)
  • return
    应该是
    continue
    ,它不是递归,return将在遍历所有树之前退出函数
  • 您需要推送节点子节点,而不是节点本身

    while (!isEmptyStack(stek))
    {
        current = pop(&stek);
    
        if (current->left != NULL)
            push(&stek, current->left);
        if (current->right != NULL)
            push(&stek, current->right);
    
        if (Depth(current) < h1)
            printf("%d ",current->info);
    }
    
    while(!isEmptyStack(stek))
    {
    电流=pop(&stek);
    如果(当前->左!=空)
    推送(&stek,当前->左);
    如果(当前->右侧!=NULL)
    推送(&stek,当前->右侧);
    if(深度(电流)信息);
    }
    
  • 正如@chux所说,如果堆栈为空,
    pop
    应该返回
    NULL


  • 我不明白在这种情况下,您的问题、输入和预期结果究竟有什么帮助,但这
    if(Depth(current)看起来不正确。为什么返回
    ?如果(isEmptyStack(*top))printf(“堆栈为空!”),则在遍历所有树之前退出该函数是一个问题。如果出现这种情况,“堆栈为空!”将发送到标准输出,但由于输出通常是缓冲的,所以还不会打印任何内容。然后代码返回未初始化的
    res
    ,带有未定义的行为结果,并且可能永远不会打印消息。最好是1)
    fprintf(stderr…
    ,或2)
    fflush(stdout)
    在打印后,或3)添加
    '\n'
    或4)只需退出代码。
    while (!isEmptyStack(stek))
    {
        current = pop(&stek);
    
        if (current->left != NULL)
            push(&stek, current->left);
        if (current->right != NULL)
            push(&stek, current->right);
    
        if (Depth(current) < h1)
            printf("%d ",current->info);
    }