I've spent hours trying to figure out why it wouldn't print the root node at the end.
It is unable to current = pop(&S);
at the last iteration.
I can't figure out what's wrong.
Algorithm:
1.1 Create an empty stack 2.1 Do following while root is not NULL a) Push root's right child and then root to stack. b)Set root as root's left child. 2.2 Pop an item from stack and set it as root. a) If the popped item has a right child and the right child is at top of stack, then remove the right child from stack, push the root back and set root as root's right child. b) Else print root's data and set root as NULL. 2.3 Repeat steps 2.1 and 2.2 while stack is not empty.
I visualized, and drew it on a whiteboard and the logic works fine to me. However when implementing it, it crashes at the last iteration.
void postOrderIterativeS1(BSTNode *root)
{
Stack S;
S.top = NULL;
BSTNode *current = root;
int shouldContinue = 1;
while(shouldContinue)
{
if(current != NULL)
{
if(current->right != NULL){
push(&S, current->right);
}
push(&S, current);
current = current->left;
}
else
{
current = pop(&S);
if(peek(&S) == NULL){
shouldContinue = 0;
}
if(current->right != NULL && peek(&S)->item == current->right->item)
{
pop(&S);
push(&S,current);
current = current->right;
}
else
{
int items= current->item;
printf("%d ", current->item);
current = NULL;
}
}
}
}
If you want the full code, https://pastebin.com/z4rPebrJ
Exeuction: