×

Morris Traversal for Inorder in Java

Through Morris’s traversal, a tree is traversed without the aid of recursion or stacks. Based on the threaded binary tree, the Morris traversal is used. We perform internal modification throughout this traverse to establish internal links for the in-order successor. We have eventually undone the alteration to bring back the original tree.

Algorithm for Morris Traversal in Order

The Morris Traversal involves the steps listed below (in Inorder).

  1. Make the current node the root initially.
  2. when the current does not equal zero

If the left child is absent from the current node

  1. Show the data for the active node.
  2. Visit the current node's right node by using the formula curr = curr -> right.

however, or else

  1. The right-hand node in the currently left subtree should be sought out.

OR

which node's right child is the active node.

If a right child equals the current node 

  1. Undo the modifications. Therefore, that right child should indeed be made to be NULL.

a node whose current node is its right child

  1. Show the data for the active node.
  2. Visit the right node by using the formula curr = curr -> right.

however, or else

  1. Making the current node the right child of both the detected rightmost node is appropriate; and
  2. Visit the curr = curr -> left child node.

Time Complexity: We note that the tree's edges are only crossed a maximum of three times. In the output tree, an equal amount of extra edges are formed and eliminated. As a result, the above program's overall time complexity is O(n).

Many places claim that the inorder traversal using a recursive technique doesn't take up any space. 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.

Program 1: For Morris traversal for inorder in java

class BTreeNode
{  
int val; 
BTreeNodelt, rt;   
BTreeNode(int item)  
{  
val = item;  
lt = rt = null;  
}  
}  


public class BTree
{  
BTreeNode rt; 
void MorrisTraversalInorder(BTreeNode rt)  
{  
BTreeNodecurr, pr;  
if (rt == null)  
{  
return;  
}  
curr = rt;  
while (curr != null)  
{  
if (curr.lt == null)  
{  
System.out.print(curr.val + " ");  
curr = curr.rt;  
}  
else   
{  
pr = curr.lt;  
while (pr.rt != null &&pr.rt != curr)  
{  
pr = pr.rt;  
}  
if (pr.rt == null)   
{  
pr.rt = curr;  
curr = curr.lt;  
} 
else  
{  
pr.rt = null;  
System.out.print(curr.val + " ");  
curr = curr.rt;  
} 
}   
}   
}  
public static void main(String argvs[])  
{  


//                        6  
//                      /   \  
//          8    9  
//                  /   \       \  
//                1      4      7  
//                       /  
//                    5  


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.MorrisTraversalInorder(tree.rt);  
}  
}  

The output of the above program

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

Program 2: For Morris traversal for inorder 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 approach
// Display the binary tree in order.
public void inorder(TreeNode node)
{
if (node != null)
{
inorder(node.left);
// Display node value
System.out.print("  " + node.data);
inorder(node.right);
}
}
// traversal of trees iteratively in order
public void morrisInorder()
{
if (this.root == null)
{
return;
}
// start at the tree's root node
TreeNode current = this.root;
TreeNode auxiliary = null;
// tree nodes iterative
while (current != null)
{
if (current.left == null)
{
// Node value to print
System.out.print("  " + current.data);
// Visit the right child when the left child is vacant.
current = current.right;
}
else
{
auxiliary = current.left;
while (auxiliary.right != null &&auxiliary.right != current)
{
auxiliary = auxiliary.right;
}
if (auxiliary.right != current)
{
// alter link
auxiliary.right = current;
current = current.left;
}
else
{
// Display node value
System.out.print("  " + current.data);
// Unlink
auxiliary.right = null;
// Visit to the right child
current = current.right;
}
}
}
System.out.print("\n");
}
public static void main(String[] args)
{
// make a new tree
BinaryTree tree = new BinaryTree();
// build a binary tree
/*  


         4
       /   \
      8     3
     / \   / \
    1   6 7   2
       /  
      9    
*/
//Nodes should be added to the tree
tree.root = new TreeNode(4);
tree.root.left = new TreeNode(8);
tree.root.left.left = new TreeNode(1);
tree.root.right = new TreeNode(3);
tree.root.right.right = new TreeNode(2);
tree.root.right.left = new TreeNode(7);
tree.root.left.right = new TreeNode(6);
tree.root.left.right.left = new TreeNode(9);
System.out.println("\n Recursive Inorder");
// Display inorder element
tree.inorder(tree.root);
System.out.println("\n Morris Inorder");
tree.morrisInorder();
}
}

The output of the above program

Recursive Inorder
1  8  9  6  4  7  3  2
 Morris Inorder
1  8  9  6  4  7  3  2

Related Topics

How to Convert String to boolean in Java

How to Convert String to boolean in Java There are two methods to convert String to boolean: Using parseBoolean(string) method Using valueOf(string) method If the string contains "True," "true," or "TRUE,"...

3 minutes read.

Jdoodle Java

Everything is instantaneous and fast-paced in the modern world. Online compilers available via the internet are immensely helpful for programmers seeking to learn a new programming language but lacking the...

4 minutes read.

Java Boolean Class

The Boolean class wraps a value of the Boolean primitive in an object. Its object contains only a single field whose type is Boolean. Boolean Methods: This class contains several different methods...

2 minutes read.

Multithreading in Java

Multithreading is a specialized form of multitasking. It is responsible for executing more than one task at a time of a single program, and each task is a separate thread. A program...

8 minutes read.

Java Worker Class

What is a Worker? A service which executes Work - flow and Activities is referred to as a Worker. On user-controlled hosts, workers are defined and put into action. The Worker...

3 minutes read.

Java Extends vs Implements

Java: We known that the java is a pure object oriented programming language. Java programming language consists of many features such as portable, plat form independence, secured, robust, simple, architecture neutral,...

4 minutes read.

Java String trim() method

Java String trim() method returns String after eliminating leading and trailing spaces. Note:- Java String trim() method doesn't trim or omit middle spaces. Syntax: public String trim() Returns: It returns string with omitted leading and...

2 minutes read.

Constructor Program in Java

Constructor Program in Java In Java, a constructor is a piece of code that is used to create an object. A constructor is called implicitly when an object is created in...

7 minutes read.

What is advance Java?

The definition of advance inside the dictionary refers to a forward motion, development, or progress, and the definition of enhancing is something that improves things. To become experts in that...

3 minutes read.

How to stop execution after a certain time in Java

We will learn how to stop a long-running execution after a set amount of time in this post. We will take a look at a few alternative approaches to this...

6 minutes read.

Java Set to List

In this article, you will be acknowledged about how the process of conversion from Set or HashSet to LinkedList happens and what are the possible ways involved in conversion process. First...

4 minutes read.

Classes and Objects in Java Example Programs

Classes and Objects in Java Example Programs Java is an Object-Oriented programming language, i.e., everything in Java is associated with objects and objects are associated with classes. The classes and objects...

5 minutes read.

How to Read XML Files in Java?

Introduction Today, we are going to learn about how to read XML files in java. Before, reading the XML Files let us learn about XML. XML Files The full form of XML is...

8 minutes read.

Creation of Multi Thread in java

What are threads in Java? We can use threads to facilitate parallel processing. Threads are helpful when you wish to execute several pieces of code concurrently. A thread is a small process...

3 minutes read.

How to Split String by Comma in Java

strsplit() technique permits you to break a string given the explicit Java string delimiter. The Java string split property is frequently a space or a comma(,) that you want to...

7 minutes read.

Web Service Response Time Calculation in Java

Administration response time or reaction time is the typical measure of time it takes for a solicitation to be handled by a PC framework, like your organization switch. In the...

4 minutes read.

Java Math sqrt() Method

The sqrt() method of Java Math class returns the accurately rounded positive square root of the specified double value. Syntax: public static double sqrt(double a) Parameters: The parameter ‘a’ represents the number whose square...

2 minutes read.

Enum Java Interview Questions

1. What exactly is Java? Java is a portable, high-level, object-oriented, robust, secure, platform-independent, multi-threaded, high-performance programming language. Developed in June 1991 by James Gosling, also known as Platform. 2. Enum is...

3 minutes read.

Bellman Ford Algorithm in Java

Numerous algorithms have been used in dynamic programming to determine the shortest path inside a graph. Among them are Floyd, all-pair shortest path problem, Breadth First Search, Depth First Search,...

6 minutes read.

Alien language problem in Java

Given the alphabetic sequence of an alien language, given a sorted dictionary (array of words) for the languages. Example: Words = { "aac", "abc", "aaa" } Output c, a, b Algorithm: (1) Compare two words that...

3 minutes read.