Advertisement
Guest User

Tree-Morris_Inorder

a guest
Mar 23rd, 2011
556
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.05 KB | None | 0 0
  1. // <-------------------[sWitCHcAsE]---------------------->
  2.  
  3. #include <iostream>
  4. #include <cstdio>
  5. #include <cstdlib>
  6. using namespace std;
  7. struct NODE {
  8.  
  9.         int data;
  10.         NODE *left;
  11.         NODE *right;
  12. };
  13.  
  14. NODE * insert(NODE *root, int data) {
  15.     if(root==NULL) {
  16.         root=(NODE*)malloc(sizeof(NODE));
  17.         root->left=root->right=NULL;
  18.         root->data=data;
  19.         return root;
  20.     }
  21.     else {
  22.         while(root!=NULL) {
  23.             if(root->data>data) {
  24.                 if(root->left!=NULL) root=root->left;
  25.                 else break;
  26.             }
  27.             else {
  28.                 if(root->right!=NULL) root=root->right;
  29.                 else break;  
  30.             }
  31.         }
  32.         NODE *new_node=new NODE;
  33.         new_node->data=data;
  34.         new_node->left=new_node->right=NULL;
  35.         if(root->data > data) {
  36.             root->left=new_node;
  37.         }
  38.         else root->right=new_node;
  39.         return new_node;
  40.     }
  41. }
  42.  
  43. void inorder(NODE *root) {
  44.     if(root!=NULL) {
  45.         inorder(root->left);
  46.         printf("%d ",root->data);
  47.         inorder(root->right);
  48.     }
  49. }
  50.  
  51. void MorrisInorder(NODE *root) {
  52.     NODE* current,*pre;
  53.     current=root;
  54.     while(current!=NULL) {
  55.         if(current->left==NULL) {
  56.             printf("%d ",current->data);
  57.             current=current->right;
  58.         }
  59.         else {
  60.             pre=current->left;
  61.             while(pre->right != NULL && pre->right !=current)
  62.                 pre=pre->right;
  63.             if(pre->right==NULL) {
  64.                 pre->right=current;
  65.                 current=current->left;
  66.             }
  67.             else {
  68.                 pre->right=NULL;
  69.                 printf("%d ",current->data);
  70.                 current=current->right;
  71.             }
  72.         }
  73.     }
  74. }
  75.  
  76. int main() {    
  77.     NODE *root=NULL;
  78.     root=insert(root,100);
  79.     insert(root,110);
  80.     insert(root,200);
  81.     insert(root,90);
  82.     insert(root,80);
  83.     insert(root,12);
  84.     insert(root,19);
  85.     insert(root,1);
  86.     insert(root,1000);
  87.     inorder(root);
  88.     cout<<endl;
  89.     cout<<"MORRIS INORDER"<<endl;
  90.     MorrisInorder(root);
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement