TheAlgorithms-C-Plus-Plus/data_structure/MorrisInorder.cpp

109 lines
2.1 KiB
C++
Raw Normal View History

#include <iostream>
#include <queue>
/**************************
@author shrutisheoran
**************************/
using namespace std;
2019-08-21 10:10:08 +08:00
struct Btree
{
int data;
2019-08-21 10:10:08 +08:00
struct Btree *left; //Pointer to left subtree
struct Btree *right; //Pointer to right subtree
};
2019-08-21 10:10:08 +08:00
void insert(Btree **root, int d)
{
Btree *nn = new Btree(); //Creating new node
nn->data = d;
nn->left = NULL;
nn->right = NULL;
2019-08-21 10:10:08 +08:00
if (*root == NULL)
{
*root = nn;
return;
}
2019-08-21 10:10:08 +08:00
else
{
queue<Btree *> q;
// Adding root node to queue
q.push(*root);
2019-08-21 10:10:08 +08:00
while (!q.empty())
{
Btree *node = q.front();
// Removing parent node from queue
q.pop();
2019-08-21 10:10:08 +08:00
if (node->left)
// Adding left child of removed node to queue
q.push(node->left);
2019-08-21 10:10:08 +08:00
else
{
// Adding new node if no left child is present
node->left = nn;
return;
}
2019-08-21 10:10:08 +08:00
if (node->right)
// Adding right child of removed node to queue
q.push(node->right);
2019-08-21 10:10:08 +08:00
else
{
// Adding new node if no right child is present
node->right = nn;
return;
2019-08-21 10:10:08 +08:00
}
}
}
}
2019-08-21 10:10:08 +08:00
void morrisInorder(Btree *root)
{
Btree *curr = root;
Btree *temp;
2019-08-21 10:10:08 +08:00
while (curr)
{
if (curr->left == NULL)
{
cout << curr->data << " ";
// If left of current node is NULL then curr is shifted to right
curr = curr->right;
}
2019-08-21 10:10:08 +08:00
else
{
// Left of current node is stored in temp
temp = curr->left;
// Moving to extreme right of temp
2019-08-21 10:10:08 +08:00
while (temp->right && temp->right != curr)
temp = temp->right;
// If extreme right is null it is made to point to currrent node (will be used for backtracking)
2019-08-21 10:10:08 +08:00
if (temp->right == NULL)
{
temp->right = curr;
// current node is made to point its left subtree
curr = curr->left;
}
// If extreme right already points to currrent node it it set to null
2019-08-21 10:10:08 +08:00
else if (temp->right == curr)
{
cout << curr->data << " ";
temp->right = NULL;
// current node is made to point its right subtree
curr = curr->right;
}
}
}
}
2019-08-21 10:10:08 +08:00
int main()
{
// Testing morrisInorder funtion
Btree *root = NULL;
int i;
2019-08-21 10:10:08 +08:00
for (i = 1; i <= 7; i++)
insert(&root, i);
2019-08-21 10:10:08 +08:00
cout << "Morris Inorder: ";
morrisInorder(root);
return 0;
}