我尝试编写Inorder树遍历而不进行递归,并将我自己的堆栈实现为数组。
代码: -
struct treenode
{
struct treenode *left;
int data;
struct treenode *right;
};
struct stack
{
int top;
unsigned capacity;
struct treenode **array;
};
void push(struct stack *stack,struct treenode *current)
{
if(isStackFull(stack))
{
printf("Stackoverflow !!");
return;
}
else
{
stack->array[++stack->top] = current;
}
}
struct treenode *pop(struct stack *stack)
{
if(isStackEmpty(stack))
{
printf("Underflow !!");
exit(0);
}
else
{
struct treenode *current = stack->array[stack->top--];
return current;
}
}
void inorderwithoutRecursion(struct treenode *tree)
{
struct stack *stack = createStack(5);
struct treenode *current = tree;
int end = 0;
while(!end)
{
if(current != NULL)
{
push(stack,current);
current = current->left;
}
else
{
if(!isStackEmpty(stack))
{
struct treenode *current = pop(stack);
printf("%d\n",current->data);
current = current->right;
}
else
{
end = 1;
}
}
}
}
struct stack *createStack(unsigned capacity)
{
struct stack *temp = malloc(sizeof(struct stack));
temp->top = -1;
temp->capacity = capacity;
temp->array = malloc(sizeof(int *) * temp->capacity);
return temp;
}
struct treenode *createTree(int value)
{
struct treenode * temp = malloc(sizeof(struct treenode));
temp->data = value;
temp->left = NULL;
temp->right = NULL;
return temp;
}
int main()
{
struct treenode *tree = createTree(1);
tree->right = createTree(2);
tree->right->left = createTree(3);
tree->right->left->right = createTree(4);
tree->right->left->right->left = createTree(5);
printf("Inorder Traversal without using recursion is: \n");
inorderwithoutRecursion(tree);
}
我的输出为: -
Inorder Traversal without using recursion is:
1
它没有给出完整的顺序遍历。好吧,它应输出13542,但这只给出一个数字。
此处没有错误,但为什么它只提供一个数字而不提供其他数字。
我在这里错过了一些细节吗?