iterative traversal of a BST

Write the iterative version of inorder,preorder and postorder traversal of a binary search tree.

Comments

  1. void inorder(struct node* p)
    {
    stack s;

    do
    {
    while(p != NULL)
    {
    s.push(p);
    p = p->left;
    }
    if(!s.empty())
    {

    p = s.top();
    s.pop();
    cout<data<right;
    }

    }while(!s.empty() || p != NULL);

    }

    void preorder(struct node* p)
    {
    stack s;

    do
    {
    while(p != NULL)
    {
    s.push(p);
    cout<data<left;
    }
    if(!s.empty())
    {
    p = s.top();
    s.pop();
    p = p->right;
    }

    }while(!s.empty() || p != NULL);

    }

    void postorder(struct node* p)
    {
    stack s;

    do
    {
    INSERT:
    while(p != NULL)
    {
    s.push(p);
    p = p->left;
    }
    if(!s.empty())
    {
    p = s.top();
    s.pop();
    if(p->right == NULL)
    cout<data<<endl;
    else goto INSERT;

    }

    }while(!s.empty() || p != NULL);

    }

    ReplyDelete

Post a Comment

Popular posts from this blog