【问题标题】:Binary search tree - Iterative check for height二叉搜索树 - 迭代检查高度
【发布时间】:2015-04-18 17:29:23
【问题描述】:

所以,我遇到了一些问题。我知道如何遍历树,是否使用递归,是否使用堆栈。但是,我也想跟踪每片叶子的高度,如果高度(或深度)小于给定的参数来打印那片叶子。这是我使用堆栈的代码:

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

我做错了什么?可能是因为我的堆栈实现?这是代码:

struct sNode{
    struct tNode* t;
    struct sNode* next;
};

/*Funkcije za stek*/
void push(struct sNode** top, struct tNode* t){
    struct sNode* newNode = (struct sNode*)malloc(sizeof(struct sNode));
    if(newNode==NULL)
    {
        return;
    }
    newNode->t = t;
    newNode->next = (*top);
    (*top) = newNode;
}

int isEmptyStack(struct sNode* top){
    return top==NULL;
}

struct tNode* pop(struct sNode** top){
    struct tNode* res;
    struct sNode* sTop;

    if(isEmptyStack(*top))
        printf("Stack is empty!");
    else{
        sTop = *top;
        res = sTop->t;
        *top = sTop->next;
        free(top);

    }
    return res;
}

问题是,我的输出只给了我根值,没有别的。有谁知道我在哪里犯了错误?还是错误:)?

【问题讨论】:

  • 我不明白在这种情况下您的问题、输入和预期结果到底有什么帮助,但是这个if(Depth(current) &lt; h1){ push(&amp;stek, current); } else return; 看起来不正确。为什么return?在遍历所有树之前退出函数
  • if(isEmptyStack(*top)) printf("Stack is empty!"); 是个问题。如果发生这种情况,“堆栈为空!”发送到stdout,但由于输出通常是缓冲的,所以还没有打印任何内容。然后代码返回未初始化的res 并带有未定义的行为结果,并且可能永远不会打印该消息。最好是 1) fprintf(stderr...,或 2) fflush(stdout) 在打印后或 3) 添加 '\n' 或 4) 简单地退出代码。

标签: c stack height binary-search-tree non-recursive


【解决方案1】:
  1. 你不要在循环内改变current的值,pop(&amp;stek)应该是current = pop(&amp;stek)
  2. return应该是continue,不是递归,return会在遍历完所有树之前退出函数
  3. 你需要推送节点子节点而不是节点本身

    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);
    }
    
  4. 正如@chux 所说,如果堆栈为空,pop 应该返回NULL

【讨论】:

    猜你喜欢
    • 2013-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-05
    • 2013-11-06
    • 1970-01-01
    • 2013-10-19
    相关资源
    最近更新 更多