# 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.

1. If the left child is null, display the data of the current node, and then move to the right child.
Else, ensure that the right child of the inorder predecessor is pointing to the current node.
Two cases come into the picture:
1. If the current node is being pointed by the right child of the inorder predecessor, then set the right child to NULL, and shift to the right child of the current node.
2. If the right child is NULL, then set it to the current node. Display the data of the current node and then shift to the left child of the current node.
2. Repeat until and unless the current node is not equal to NULL.

### Implementation

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

FileName: BTree1.java

Output:

```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.