Skip to content

Latest commit

 

History

History
55 lines (43 loc) · 1.15 KB

File metadata and controls

55 lines (43 loc) · 1.15 KB

Postorder Traversal Practice

Recursive method

 vector<int>v;
    vector<int> postorderTraversal(TreeNode* root) {
         if(root==NULL)
            return v;

        v=postorderTraversal(root->left);
        v=postorderTraversal(root->right);
        v.push_back(root->val);
        return v;
    }

Iterative method

 
     vector<int> postOrder(Node* node) {
      
      stack<Node*> s;
      vector<int> v;
      
      s.push(node);
      
      while(!s.empty())
      {
          Node* tp=s.top();
          int flag=0;
          if(tp->right!=NULL)
           {
               s.push(tp->right);
               tp->right=NULL;
               flag=1;
           }
           
           if(tp->left!=NULL)
           {
               s.push(tp->left);
               tp->left=NULL;
               flag=1;
           }
           
           if(flag==0)                 //tp is leaf node
           {
               v.push_back(tp->data);
               s.pop();
           }
      }
      return v;
   }