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(深度(电流)信息);
}
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);
}