Morris Traversal for Preorder in Java
In this section, we will learn about the Morris traversal for preorder 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.
Morris Traversal Preorder Algorithm
The following is the algorithm for the Morris traversal for the preorder, which is almost similar to the Morris traversal for the inorder.
Let's see the implementation of the Morris traversal for the preorder using the algorithms described above.
The preorder traversal of the binary tree is: 6 8 1 4 5 9 7
Time Complexity: Since the algorithm is similar to the Morris traversal for the inorder. Therefore, 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 preorder 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. Therefore, if the internal modification is not allowed, one should look after the Morris traversal.
Next TopicPackage Naming Conversion in Java