Tree: Postorder Traversal

  • + 0 comments

    An iterative solution

    struct stackEle{
            Node *n;
            int c;
            stackEle(Node *n,int c)
            {
                this->n = n;
                this->c = c;
            }
        };
    
        void postOrder(Node *root) {
            stack<stackEle> s;
            Node *cur = root;
            int c = 0;
            do{
                if(cur==NULL){
                    if(s.empty())
                        break;
                    else{
                        stackEle e = s.top();
                        s.pop();
                        cur = e.n;
                        c = e.c;
                    }
                }else{
                    if(c==0){
                        s.push(stackEle(cur,1));
                        cur = cur->left;
                        c = 0;
                    }else if(c==1){
                      s.push(stackEle(cur, 2));
                      cur = cur->right;
                      c = 0;
                    }else{
                        cout<<cur->data<<" ";
                        if(s.empty())
                            break;
                        else{
                          stackEle e = s.top();
                          s.pop();
                          cur = e.n;
                          c = e.c;
                        }
                    }
                }
            }while(1);
        }