jain12

postorder traversal without recursion in a binary tree

Mar 30th, 2020
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.84 KB | None | 0 0
  1. #include<iostream>
  2. #include<stack>
  3. using namespace std;
  4.  
  5. class Node{
  6.   public:
  7.       int data;
  8.       Node *left,*right;
  9.       Node(int key){
  10.         data=key;
  11.         left=NULL;
  12.         right=NULL;
  13.         }
  14.   };
  15.  
  16. void Postorder(Node* root){
  17.   if(root==NULL)
  18.     return;
  19.   stack<Node*>s;
  20.   stack<int>out;
  21.   s.push(root);
  22.   while(!s.empty()){
  23.     Node* temp=s.top();
  24.     s.pop();
  25.     out.push(temp->data);
  26.     if(temp->left)
  27.         s.push(temp->left);
  28.     if(temp->right)
  29.         s.push(temp->right);
  30.     }
  31.   while(!out.empty()){
  32.     cout<<" "<<out.top();
  33.     out.pop();
  34.     }
  35.   }
  36.  
  37. int main(){
  38.   Node* root=NULL;
  39.   Node* newnode=new Node(1);
  40.   root=newnode;
  41.   root->left=new Node(9);
  42.   root->right=new Node(3);
  43.   (root->left)->left=new Node(2);
  44.   (root->right)->right=new Node(4);
  45.   Postorder(root);
  46.   return 0;
  47.   }
Add Comment
Please, Sign In to add comment