#include<stdio.h>
#include<stdlib.h>
#include <iostream>
using namespace std;
/* A binary tree tNode has data, pointer to left child
and a pointer to right child */
struct tNode
{
int data;
struct tNode* left;
struct tNode* right;
};
struct tNode* findBSTMin(struct tNode *root) {
if(!root) { return root;}
while(root->left) {
root = root->left;
}
return root;
}
struct tNode* successorBST(struct tNode *curr, struct tNode *root) {
if(!curr) { return curr;}
if(curr->right) {
return findBSTMin(curr->right);
}
struct tNode* successor = 0;
while(root && root != curr) {
if(curr->data < root->data) {
successor = root;
root = root->left;
} else {
root = root->right;
}
}
return successor;
}
void InOrderIteravtiveNoStack(struct tNode *root) {
if(!root) { return; }
struct tNode *curr = findBSTMin(root);
while(curr) {
cout << curr->data << " ";
curr = successorBST(curr, root);
}
return;
}
/* Function to traverse binary tree without recursion and
without stack */
void MorrisTraversal(struct tNode *root)
{
struct tNode *current,*pre;
if(root == NULL)
return;
current = root;
while(current != NULL)
{
if(current->left == NULL)
{
printf(" %d ", current->data);
current = current->right;
}
else
{
/* Find the inorder predecessor of current */
pre = current->left;
while(pre->right != NULL && pre->right != current)
pre = pre->right;
/* Make current as right child of its inorder predecessor */
if(pre->right == NULL)
{
pre->right = current;
current = current->left;
}
/* Revert the changes made in if part to restore the original
tree i.e., fix the right child of predecssor */
else
{
pre->right = NULL;
printf(" %d ",current->data);
current = current->right;
} /* End of if condition pre->right == NULL */
} /* End of if condition current->left == NULL*/
} /* End of while */
}
/* UTILITY FUNCTIONS */
/* Helper function that allocates a new tNode with the
given data and NULL left and right pointers. */
struct tNode* newtNode(int data)
{
struct tNode* tNode = (struct tNode*)
malloc(sizeof(struct tNode));
tNode->data = data;
tNode->left = NULL;
tNode->right = NULL;
return(tNode);
}
/* Driver program to test above functions*/
int main()
{
/* Constructed binary tree is
5
/ \
2 6
/ \
1 4
*/
struct tNode *root = newtNode(5);
root->left = newtNode(2);
root->right = newtNode(6);
root->left->left = newtNode(1);
root->left->right = newtNode(4);
//MorrisTraversal(root);
InOrderIteravtiveNoStack(root);
getchar();
return 0;
}