|
| 1 | +#include <iostream> |
| 2 | +#include <queue> |
| 3 | + |
| 4 | +/************************** |
| 5 | + @author shrutisheoran |
| 6 | +**************************/ |
| 7 | + |
| 8 | +using namespace std; |
| 9 | + |
| 10 | +struct Btree { |
| 11 | + int data; |
| 12 | + struct Btree* left; //Pointer to left subtree |
| 13 | + struct Btree* right; //Pointer to right subtree |
| 14 | +}; |
| 15 | + |
| 16 | +void insert(Btree **root, int d) { |
| 17 | + Btree *nn = new Btree(); //Creating new node |
| 18 | + nn->data = d; |
| 19 | + nn->left = NULL; |
| 20 | + nn->right = NULL; |
| 21 | + if(*root == NULL) { |
| 22 | + *root = nn; |
| 23 | + return; |
| 24 | + } |
| 25 | + else { |
| 26 | + queue<Btree*> q; |
| 27 | + // Adding root node to queue |
| 28 | + q.push(*root); |
| 29 | + while(!q.empty()) { |
| 30 | + Btree *node = q.front(); |
| 31 | + // Removing parent node from queue |
| 32 | + q.pop(); |
| 33 | + if(node->left) |
| 34 | + // Adding left child of removed node to queue |
| 35 | + q.push(node->left); |
| 36 | + else { |
| 37 | + // Adding new node if no left child is present |
| 38 | + node->left = nn; |
| 39 | + return; |
| 40 | + } |
| 41 | + if(node->right) |
| 42 | + // Adding right child of removed node to queue |
| 43 | + q.push(node->right); |
| 44 | + else { |
| 45 | + // Adding new node if no right child is present |
| 46 | + node->right = nn; |
| 47 | + return; |
| 48 | + } |
| 49 | + } |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +void morrisInorder(Btree *root) { |
| 54 | + Btree *curr = root; |
| 55 | + Btree *temp; |
| 56 | + while(curr) { |
| 57 | + if(curr->left==NULL) { |
| 58 | + cout<<curr->data<<" "; |
| 59 | + // If left of current node is NULL then curr is shifted to right |
| 60 | + curr = curr->right; |
| 61 | + } |
| 62 | + else { |
| 63 | + // Left of current node is stored in temp |
| 64 | + temp = curr->left; |
| 65 | + // Moving to extreme right of temp |
| 66 | + while(temp->right&&temp->right!=curr) |
| 67 | + temp = temp->right; |
| 68 | + // If extreme right is null it is made to point to currrent node (will be used for backtracking) |
| 69 | + if(temp->right == NULL) { |
| 70 | + temp->right = curr; |
| 71 | + // current node is made to point its left subtree |
| 72 | + curr = curr->left; |
| 73 | + } |
| 74 | + // If extreme right already points to currrent node it it set to null |
| 75 | + else if(temp->right == curr) { |
| 76 | + cout<<curr->data<<" "; |
| 77 | + temp->right = NULL; |
| 78 | + // current node is made to point its right subtree |
| 79 | + curr = curr->right; |
| 80 | + } |
| 81 | + } |
| 82 | + } |
| 83 | +} |
| 84 | + |
| 85 | +int main() { |
| 86 | + // Testing morrisInorder funtion |
| 87 | + Btree *root = NULL; |
| 88 | + int i; |
| 89 | + for(i = 1 ; i <= 7 ; i++) |
| 90 | + insert(&root, i); |
| 91 | + cout<<"Morris Inorder: "; |
| 92 | + morrisInorder(root); |
| 93 | + return 0; |
| 94 | +} |
0 commit comments