转自https://www.geeksforgeeks.org/inorder-tree-traversal-without-recursion-and-without-stack/
Inorder Tree Traversal without recursion and without stack!
Using Morris Traversal, we can traverse the tree without using stack and recursion. The idea of Morris Traversal is based on Threaded Binary Tree. In this traversal, we first create links to Inorder successor and print the data using these links, and finally revert the changes to restore original tree.
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 跳到左分支
Although the tree is modified through the traversal, it is reverted back to its original shape after the completion. Unlike Stack based traversal, no extra space is required for this traversal.
|
Run on IDE
Output:
4 2 5 1 3
Time Complexity : O(n) If we take a closer look, we can notice that every edge of the tree is traversed at-most two times. And in worst case same number of extra edges (as input tree) are created and removed.
References:
www.liacs.nl/~deutz/DS/september28.pdf
www.scss.tcd.ie/disciplines/software_systems/…/HughGibbonsSlides.pdf
Please write comments if you find any bug in above code/algorithm, or want to share more information about stack Morris Inorder Tree Traversal.