Javatpoint Logo
Javatpoint Logo

Morris Traversal for Inorder in Java

In this section, we will learn about the Morris traversal for inorder in Java. In Morris traversal, we do the traversal of a tree without the help of recursion or stack. The Morris traversal is based on the threaded binary tree. In this traversal, we do the internal modification in order to create the internal links for the inorder successor. Eventually, we revert the modification so that the original tree is restored.

Morris Traversal Inorder Algorithm

The following are the steps involved in the Morris Traversal (Inorder).

  1. Initialize the current node as the root
  2. While the current is not equal to NULL
    Whenever the current node does not have the left child
    1. Display the data of the current node
    2. Visit the right node of the current node, i.e., curr = curr -> right
      Otherwise / Else
      1. Look for the rightmost node in the current left subtree
        The node whose right child is the current node.
        If the right child == curr node (current node)
        1. Revert the changes. It means the right child should be made as NULL of that
          a node whose right child is the current node
        2. Display the data of the current node
        3. Visit the right node, i.e., curr = curr -> right
          Otherwise / Else
          1. The current node should be made the right child of the rightmost node whichwe found; and
          2. Visit this left child node, i.e., curr = curr -> left


Let's see the implementation of the Morris traversal for the inorder using the algorithms described above.



The inorder traversal of the binary tree is: 
1 8 4 6 9 7

Time Complexity: We observe that every edge of the tree is traversed at most 3 times. The same number of extra edges, as in the input tree, is removed and created. Thus, the total time complexity of the above program is O(n).

Note: At many places, it is said that in recursive approach for doing the inorder traversal does not consume any space. However, this is not true. In recursion, a stack is used, even though we do not provide the stack explicitly.

The Morris traversal can work with the help of the internal modification done in the binary tree. Without internal modification, the Morris traversal cannot work.

Youtube For Videos Join Our Youtube Channel: Join Now


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Trending Technologies

B.Tech / MCA