所以,我有一点问题。我知道如何遍历树,是否使用递归,是否使用堆栈。但是,我也想跟踪每片叶子的高度,如果高度(或深度)小于给定的参数来打印那片叶子。这是我使用堆栈的代码:
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;
}
问题是,我的输出只给了我根值,没有别的。有谁知道我在哪里犯了错误?还是错误:)?