×

Morris Traversal for Preorder in Java

Without the use of recursion or stacks, we traverse a tree using the Morris algorithm. The linked binary tree is the foundation of the Morris traversal.

Preorder Morris Traversal Algorithm

The preorder Morris traversal algorithm, which is nearly identical to the inorderMorris traversal, is given below.

1. Move on to the right child after displaying the contents of the current node if indeed the left child is null.

Otherwise, check to make sure the correct child of the in-order predecessor is directed at the current node.

Two situations are involved:

  • If the right child of both the inorder predecessor is pointing to the current node, set that child to NULL and move on to the right child of the current node.
  • Set the right child of both inorder predecessors that are pointing to the current node to NULL and then proceed on to the right child of the current node if necessary.

2. Repeat if and only if the present node is not NULL.

Features

Due to the algorithm's resemblance towards the Morris traverse for the inorder, time complexity. Thus, O represents the program's overall time complexity (n).

Preorder traversal using a recursive technique is stated to not take up any space in several locations. This is untrue, though. Even if we don't explicitly offer the stack, recursion uses one.

The internal alteration made to the binary tree allows the Morris traversal to function. The Morris traversal never functions without internal change. Therefore, one should take care of the Morris traversal if the internal alteration is not permitted.

Program 1: For the Morris traversal preorder in java

import java.io.*;
import java.util.*;
class BTreeNode
{  
int val;
BTreeNodelt, rt;   
BTreeNode(int item)  
{  
val = item;  
lt = rt = null;  
}  
}  
public class BTree1   
{  
BTreeNode rt;  
void morrisTrvrslPreorder(BTreeNode r)   
{  
while (r != null)   
{  
if (r.lt == null)   
{  
System.out.print(r.val + " ");  
r = r.rt;  
}   
else   
{  
BTreeNodecurr = r.lt;  
while (curr.rt != null &&curr.rt != r)   
{  
curr = curr.rt;  
}  


if (curr.rt == r)   
{  
curr.rt = null;  
r = r.rt;  
}  
else   
{  
System.out.print(r.val + " ");  
curr.rt = r;  
r = r.lt;  
}  
}  
}  
}  


public static void main(String argvs[])  
{  
BTree tree = new BTree();  
tree.rt = new BTreeNode(6);  
tree.rt.lt = new BTreeNode(8);  
tree.rt.rt = new BTreeNode(9);  
tree.rt.lt.lt = new BTreeNode(1);  
tree.rt.lt.rt = new BTreeNode(4);  
tree.rt.rt.rt = new BTreeNode(7);  
tree.rt.lt.rt.lt = new BTreeNode(5);  
System.out.print("The inorder traversal of the binary tree is: \n" );  
tree.morrisTrvrslPreorder(tree.rt);  
}  
}   

The output of the above program

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

Program 2: For the Morris traversal preorder in java

// Binary Tree Node
class TreeNode
{
public int data;
public TreeNode left;
public TreeNode right;
public TreeNode(int data)
{
// Define node value
this.data = data;
this.left = null;
this.right = null;
}
}
public class BinaryTree
{
public TreeNode root;
public BinaryTree()
{
// Root's starting value should be set.
this.root = null;
}
//  Recursive procedure
//Display the binary tree's preorder view.
public void preorder(TreeNode node)
{
if (node != null)
{
// Display node value
System.out.print("  " + node.data);
preorder(node.left);
preorder(node.right);
}
}
// preorder tree traversal that is iterative
public void morrisPreorder()
{
if (this.root == null)
{
return;
}
TreeNode current = this.root;
TreeNode auxiliary = null;
// tree nodes being iterated
while (current != null)
{
if (current.left == null)
{
// display node value
System.out.print("  " + current.data);
// Visit the right children
current = current.right;
}
else
{
auxiliary = current.left;


                // Locate the rightmost node that is not 
                // similar to the current node
while (auxiliary.right != null &&
auxiliary.right != current)
{
auxiliary = auxiliary.right;
}
if (auxiliary.right != current)
{
// display node value
System.out.print("  " + current.data);
// Link the current node to the rightmost right node.
auxiliary.right = current;
current = current.left;
}
else
{      
auxiliary.right = null;
current = current.right;
}
}
}
System.out.print("\n");
}
public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();
tree.root = new TreeNode(4);
tree.root.left = new TreeNode(8);
tree.root.left.left = new TreeNode(1);
tree.root.right = new TreeNode(10);
tree.root.right.right = new TreeNode(-3);
tree.root.right.left = new TreeNode(7);
tree.root.left.right = new TreeNode(6);
tree.root.let.right.left = new TreeNode(9);
System.out.println("\n Recursive Preorder");
tree.preorder(tree.root);
System.out.println("\n Morris Preorder");
tree.morrisPreorder();
}
}

The output of the above program

Recursive Preorder
4  8  1  6  9  10  7  -3
 Morris Preorder
4  8  1  6  9  10  7  -3

Related Topics

Reentrant Lock in Java

The Lock interface is implemented by the ReentrantLock class, which also provides methods for synchronising access to shared resources. The code that controls the resource has calls to the lock...

4 minutes read.

Java Integer rotateRight() method

The rotateRight() method of Java Integer class returns the value obtained by rotating the  2’s complement binary representation of the given integer value right by the specified number of bits. Syntax public...

1 minute read.

Getter and Setter Method in Java Example

In Java programming, getter and setter methods are often employed. The values of class fields can be accessed and changed using Java's getter and setter methods. A private access specifier...

6 minutes read.

Java Thread Priority in Multithreading

As we realise, java, being object-situated, works inside a multithreading climate in which the string scheduler relegates the processor to a string in light of the need for a string....

6 minutes read.

Difference between Aggregation and Composition in Java

What is Aggregation? Before we start discussing Aggregation, we have to know some general information about our classes in java. Generally we have two members in our classes , the first...

8 minutes read.

Nested Enum in Java

A class that can be defined within another class is called a nested class in Java. You can logically group classes that are used onlyin one place. This makes encapsulation...

3 minutes read.

Implementing Queue Using Array in Java

We can implement queue by using array in Java. The queue is a linear data structure, and the array is one of the simplest data structures. Before implementing a queue...

4 minutes read.

Java 8 Features

Java 8 Features: After the great success of Java 7, many developers were waiting for the next version of one of the best languages in the tech world. Moreover, on...

6 minutes read.

Web Crawler in Java

In this article, you will be acknowledged with what a web crawler in java is and what are its functions. You will also be able to understand where to implement...

4 minutes read.

Menu Driven Program in Java

Menu Driven Program in Java The menu-driven program in Java is a program that displays a menu and then takes input from the user to choose an option from the displayed...

3 minutes read.

Access specifiers in Java

What are access specifiers in Java? Access specifiers in Java are used to determine whether other classes can use a particular field or invoke a particular method. Access specifiers mainly specify...

7 minutes read.

How to Split the String in Java with Delimiter

In Java, splitting strings is a significant and typically used activity while coding. Java gives different ways of dividing the String. The most widely recognized way is to use the...

3 minutes read.

Java String Inbuilt functions

There are different types of inbuilt functions available in the Java String class, all of them are listed below. Char chat At (int index)It outputs the character indicated by the index....

5 minutes read.

Operators in Java

There is a good operator environment provided by Java. These operators are divided into four different groups i.e. arithmetic, bitwise, relational, and logical. There are other operators also available to...

7 minutes read.

Java Math addExact() Method

The addExact() method of Math class returns the sum of the two arguments, throwing an exception if the result overflows a long or an int. Syntax public static int addExact (int x,...

1 minute read.

Java Math with Methods and Examples

Java Math class contains various methods for performing math operations like min(), max(), avg() and various trigonometric functions like sin(), cos(), tan() etc. Methods: The java.lang.Math class contains various methods for performing...

5 minutes read.

Java Integer toOctalString() method

The toOctalString() method of Java Integer class returns a string representing the specified int argument as an unsigned integer in base 8. Syntax public static String toOctalString (int  i) Parameters The parameter ‘i’ represents...

1 minute read.

Sum of digits in string in java

To find the sum of all digits in a string, you need to traverse through the string one by one character; if the character is an integer, you need to...

2 minutes read.

Pig Latin Program in Java

Pig Latin Program in Java Pig Latin is a method for translating words of the English language into a different language. It is an encrypted word that is generated by using the following steps....

4 minutes read.

Reverse a String using Collections in Java

Generally, a String is a grouping of characters. Yet, in Java, a String is an item that addresses a succession of characters. The Java.lang.String class is utilized to make a...

5 minutes read.