Search code examples
clinked-listtreestackinorder

Inorder Traversal Iterative Method


This is my code for iterative Inorder Traversal. It is not giving me the output at all, all it does is show me a blank screen. It will be really helpful if someone can review my code and tell me where am I making a mistake.

void iterativeInorder(struct node *root) {
    if(root==NULL) {
        return;
    }
    struct node *stack[100];
    int top=0;
    while(root) {
        if(root!=NULL) {
            stack[top++]=root;
            root=root->left;
        }
        else {
            if(top==0) {
                break;
            }
            root=stack[--top];
            printf("%d ", root->data);
            root=root->right;
        }
    }
}

Solution

  • The error is in the while-condition. Think of it: when the while-condition is true, then also the next if-condition is true, and so you'll never get into the else-block.

    The only time you should exit the loop is when you hit this break:

    if(top==0) {
        break;
    }
    

    So, fix your code by turning your while into:

    while(true) {