hi Chang ,
how abt this. u need not set the right ptr to null. just allow one extra pointer bubble thro the popped out nodes.
 

int nr_postorder(Tree *temp){

                          Tree *store=root;

                          while(temp != NULL || top !=-1) {

                                   if(temp!=NULL){

                                            push(temp); temp=temp->left;

                                   }

                                   else {

                                           temp=pop();

                                          while(temp->right == NULL || temp->right == store) {

                                                     printf("%d ",temp->data);

                                                     store = temp; temp=pop();

                                                     if(top==-2)     return 1;}

                                     push(temp);store=temp=temp->right;

                                     }

                         }

                        return 0;

}

if any errors  found please correct me.
 
On 5/14/06, Thomas.Chang <[EMAIL PROTECTED]> wrote:

Hi,

   I got an iterative version of postorder traversal for a binary tree.
   But I guess there must be some better way to implement it, still in
iterative way.

   Here comes the code:

void iter_postorder(tree_pointer ptr){
   int top = -1;
   for(;;){
       if(ptr){
           for(;ptr;ptr=ptr->left_child){
               addstack(&top, ptr);
           }
           ptr = ptr->right_child;
           while(!ptr){
               if(stack[top]->right_child){
                   ptr = stack[top]->right_child;
                   stack[top]->right_child = NULL;
/*note that the original tree is changed.
if leave it unchanged, we may need to copy this node to a newly malloced
area, and set the right_child to NULL.
anyway, seems a little ugly.  */
                   break;
               }
               deletestack(ptr);
               if(!ptr)
                   return;
               printf("%d", ptr);
           }
       }
   }
}

Thomas.Chang


--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Algorithm Geeks" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at http://groups.google.com/group/algogeeks
-~----------~----~----~----~------~----~------~--~---

Reply via email to