Advertisement
apl-mhd

inorderTraversalWithoutRecursion

Apr 20th, 2017
621
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.42 KB | None | 0 0
  1. /*mmahmud161036@bscse.uiu.ac.bd */
  2.  
  3. #include <iostream>
  4. #include <cstdio>
  5.  
  6. using namespace std;
  7.  
  8. struct tree{
  9.     char data;
  10.     struct tree *left;
  11.     struct tree  *right;
  12.  
  13. };
  14.  int index=-1;
  15. typedef struct tree tree;
  16.  tree *stack[100];
  17. tree *insert(tree *root){
  18.      
  19.      char ch;
  20.      
  21.      printf("%c has any Left child: ", root->data);
  22.         cin>>ch;
  23.         if(ch == 'y'){
  24.             root->left = new tree();
  25.             cout<<"Enter left child\n";
  26.             cin>>root->left->data;
  27.             insert(root->left);
  28.             }
  29.         else
  30.             root->left =NULL;
  31.            
  32.         printf("%c has any Right child:", root->data);
  33.         cin>>ch;
  34.        
  35.         if(ch == 'y'){
  36.             root->right = new tree();
  37.             cout<<"Enter right child\n";
  38.             cin>>root->right->data;
  39.             insert(root->right);
  40.             }
  41.         else
  42.             root->right = NULL;
  43. return root;     
  44. }
  45.  
  46.  
  47.  
  48. void push(tree *x){
  49.    
  50.     index++;
  51.    
  52.     stack[index]  = x;
  53.    
  54. }
  55. void pop(){
  56.    
  57.     index -=1;
  58. }
  59.  
  60. tree *top(){
  61.    
  62.    
  63.     return stack[index];
  64. }
  65.  
  66. bool empty(){
  67.    
  68.     if(index <0)
  69.         return true;
  70.        
  71.     return false;
  72.  
  73. }
  74.  
  75. void inorder(tree *root){
  76.     tree *x;
  77.     while(true){
  78.        
  79.         if(root !=NULL){
  80.            
  81.             push(root);
  82.             root=root->left;
  83.            
  84.             }
  85.         else{
  86.             if(empty())
  87.                 break;
  88.             x = top();
  89.             cout<<x->data;
  90.             pop();
  91.             root = x->right;   
  92.            
  93.             }
  94.            
  95.        
  96.     }
  97.    
  98. }
  99.  
  100.  
  101. int main(int argc, char **argv)
  102. {
  103.  
  104.    
  105.     tree *root;
  106.     root = new tree();
  107.     root->data = 'A';  
  108.     insert(root);
  109.     inorder(root);
  110.    
  111.    
  112.    
  113.    
  114.     return 0;
  115. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement