Click here to Login

Non Recursive algorithms for inorder,preorder and postorder traversals(Binary tree Traversals)


Binary Tree Traversals (Non Recursive)

preorder(Node temp)
{
     Node ptr;
     ptr=temp;
     while(ptr!=NULL||top!=-1)
     {
                     if(ptr!=NULL)
                     {
                                  Print ptr->data
                                  push(ptr);
                                  ptr=ptr->lchild
                     }
                     else
                     {
                         ptr=pop();
                         ptr=ptr->rchild;
                     }
     }
}

inorder(Node temp)
{
     Node ptr;
     ptr=root;
     while(ptr!=NULL||top!=-1)
     {
                     if(ptr!=NULL)
                     {
                                  push(ptr);
                                  ptr=ptr->lchild;
                     }
                     else
                     {
                         ptr=pop();
                         print ptr->data;
                         ptr=ptr->rchild;
                     }
     }
}

postorder(Node temp)
{
     Node ptr;
     ptr=root;
     do
     {
      while(ptr!=NULL)
      {
            push(ptr->rchild);
            push(ptr);
            ptr=ptr->lchild;
           
      }
      ptr=pop();
      if((ptr->rchild!=NULL)&&(ptr->rchild==info[top]))
      {
         pop();
         push(ptr);
         ptr=ptr->rchild;
      }              
      else
      {
         Print ptr->data
         ptr=NULL;
      }
     }while(top!=-1);
}


0 comments:

Post a Comment