【发布时间】: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) < h1){ push(&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