×

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

GCD of Different SubSequences in Java

The positive numbers are provided in an array called inArr. The aim is to determine the number of distinct GCDs (Greatest Common Divisors) in each subsequence present in the input...

4 minutes read.

Java Switch string

A multi-way branch statement is the switch statement. It offers a simple method for allocating execution to various code sections according to the expression's value. Primitive data types, including bytes,...

3 minutes read.

Polymorphism Program in Java

Polymorphism Program in Java: Polymorphism means the existence of different forms of an object. The object can be a class object or a real-time entity. For example, a person can...

5 minutes read.

Java Continue Keyword

The java keyword ‘continues’ has also been called as java continue statement.The main concepts of the java continue statement or keyword is used in the controlling of the loop structure.Java...

3 minutes read.

Grepcode Java util date

What is java.util.Date Class? The date and time in Java are provided through the java.util.Date class. If you imported java.util, it could be helpful. Use the Java.util.Date class to implement this class...

4 minutes read.

Swapping Program in Java

Swapping Program in Java The swapping program in Java is used to interchange the values of the two variables. For example, if X = 12 and Y = 24, then the...

4 minutes read.

String Concatenation in Java

In Java, it gathers a new String that combines several strings. Following are the manners to concatenate strings in Java: By + (String concatenation) operatorBy concat() method By + (String concatenation) operator Java...

4 minutes read.

How to find length of integer in Java

We can find the length of the integer in many ways. The length of an integer is defined as the count of the number of digits for the given integer. These...

5 minutes read.

Array Programs in Java

Array Programs in Java: An array is a data structure that stores similar elements in a contiguous memory location. In Java, an array is an object that stores the same...

7 minutes read.

How to compare two dates in different format in Java?

We need to compare two dates frequently when coding. Real-world examples include sorting a list of persons by age or keeping track of students' attendance. To compare two dates, we...

7 minutes read.

Java Queue Interface

Queue interface is a subtype of Collection interface. All methods in the Collection interface are also available in the Queue interface. It provides operations of Collection and also some additional...

2 minutes read.

Constructor Overloading in Java

In Java, constructors can be overloaded just like methods. The idea of having multiple constructors with various parameter sets so that each function Object()  can carry out a particular task...

3 minutes read.

Hashtable in Java

Hashtable in Java The Hashtable class implements the Map interface and extends the Dictionary class. It implements a hash table which shows the key-value relation, i.e., it maps the keys to the values....

9 minutes read.

Java IO

It is a part of java libraries but is often known as I/O streams, file I/O, and file handling. The Java I/O concept satisfies the need for input processing and...

4 minutes read.

Java Boolean toString() Method

The toString() method of Java Boolean class returns a String corresponding to this Boolean object. It returns a string value “true”, if the defined object is true else it returns...

2 minutes read.

How to Convert Octal to Decimal in Java

How to Convert Octal to Decimal in Java There are two methods to convert Octal to Decimal: Using parseInt() method Using user-defined logic Using Integer.parseInt() method The Integer.parseInt() method is a static method...

2 minutes read.

The Maximum Rectangular Area in a Histogram in Java

Continuous bars should be used to form the largest possible rectangle. We'll assume in the interest of convenience that each bar's width is 1. Naive Approach In this method, each bar will be...

6 minutes read.

Buffer reader to read string in Java

The Buffered Reader class of Java is used to read the stream of characters from the input stream. Program to read string using Buffer reader import java.io.*; class  Demo {   public static void main(String...

3 minutes read.

Java Editors

A straightforward text editor may be used to create Java applications. However, a Java integrated programming environment (IDE) enables the software developer to create programs more quickly. An IDE offers...

4 minutes read.

Properties Class in Java

Properties class is associated with Java since JDK 1.0, i.e. it is a legacy class. It is the subclass of Hashtable. It is used to maintain the lists of values in which...

5 minutes read.