参考:http://pthread.blog.163.com/blog/static/169308178201210112045787/
Most textbooks mention that binary tree can be traversed using recursion or , using stack without recursion. The recursive procedure is simple to write, and the stack version use extra space.
1. Initialize current as root
2. While current is not NULL
If current does not have left child
a) Print current’s data
b) Go to the right, i.e., current = current->right
Else
a) Make current as right child of the rightmost node in current's left subtree
b) Go to this left child, i.e., current = current->left
The algorithm is also very easy to implementation:
template<typename T>
void morris_traversal(bst_node_t<T>* root)
{
bst_node_t<T>* current = root;
while (current) {
if (!current->left) {
std::cout << current->data << " ";
current = current->right;
} else {
bst_node_t<T>* it = current->left;
while (it->right && it->right != current) {
it = it->right;
}
if (!it->right) {
it->right = current;
current = current->left;
} else {
std::cout << current->data << " ";
it->right = NULL;
current = current->right;
}
}
}
}


/*
here current points to node 8,it to node 3
*/
bst_node_t<T>* it = current->left;
/*
go to che right most child of node 3 that is node 7
*/
while (it->right && it->right != current) {
it = it->right;
}
/*
here it points to node 7, current to node 8
*/
if (!it->right) {
/*
set current(node 8) as right child of node 7, notice
that node 8's left child pointer still points to node 3
*/
it->right = current;
/*
current goes left, that is, current points to node 3
*/
current = current->left;
}

if (!current->left) {
std::cout << current->data << " ";
current = current->right;
}

/*
current => node 3
it => node 1
*/
bst_node_t<T>* it = current->left;
/*
here we find that it->right = node 3 = current
so break the loop
*/
while (it->right && it->right != current) {
it = it->right;
}
if (!it->right) {
it->right = current;
current = current->left;
} else {
/*
we visit node 3 in the second time, thus print data
*/
std::cout << current->data << " ";
/*
adjust node 1's right child pointer to null as it originally be
*/
it->right = NULL;
/*
we complete traversal left child of node 3, current goes right, that is node 5
*/
current = current->right;
}