×

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

Java Math nextAfter() Method

The nextAfter() method of Math class returns the floating-point value adjacent to the first argument in direction of the second argument. Syntax: public static double nextAfter (double start, double direction)public static float...

2 minutes read.

Short Circuit Logical Operators in Java

When there are two or more relational expressions in a decision-making statement, logical operators are utilized to combine them. The logical operators short circuit and not-short circuit fall into two...

5 minutes read.

Java Map Interface

A map is a collection that maps keys to values, with no duplicate keys allowed. The elements in a map are key/value pairs. HashMap: HashMap stores the keys in a...

3 minutes read.

Java Keywords

Java Keywords The particular words which are used in java programming language that act like a key or important words to write a code are called java keywords. Java Keywords are...

4 minutes read.

Hashing Algorithm in Java

The hashing algorithm is a method that maps data to the fixed-length hash. The Java hash-based algorithm employs a cryptographic mathematical operation. A hash technique or hash function is supposed...

8 minutes read.

Java vs Node.js

Java: Java is an object oriented programming language. It is also known as multi threaded language. It was designed by James gosling in the year 1995. We can also say that...

4 minutes read.

Convert milliseconds to date in Java

In Java, we frequently need to convert milliseconds into Dates with several formats, including dd MM yyyy and dd MM yyyy HH:mm:ss:SSS Z, among others. The Date class is one of the most...

4 minutes read.

Java Integer signum() method

The signum() method of Java Integer class returns the signum function of the specified int value. Syntax public static int signum (int i)  Parameters The parameter ‘i’ represents the value whose signum is to...

1 minute read.

What’s new in Java 12

On March 19th, 2019, the Java 12th edition was released. After releasing this edition, they have decided to release every new edition every six months. This version is the advanced...

5 minutes read.

Enterprise Java Beans

One of the many Java APIs for the common development of corporate software is Enterprise Java Beans (EJB). An EJB, a server-side software component, contains the business logic of an...

4 minutes read.

Sierpinski Number in Java

The Sierpinski triangle—is it a fractal? The Sierpinski Triangle fractals. A self-similar fractal is the Sierpinski triangle. It is made of an equilateral triangle with its residual area successively reduced by...

3 minutes read.

Upcasting and Downcasting in Java

Type casting in Java is an important and very interesting topic to deal with. But here upcasting and downcasting is somewhat related to typecasting. In normal typecasting, we convert from...

6 minutes read.

Volatile keyword in Java

Multiple threads can change a variable's value by using the volatile keyword. Making classes thread-safe is another application for it. It indicates that using a method or an instance of...

3 minutes read.

Zig Zag star and Number Pattern in Java

We covered many Java pattern applications in the preceding part. We will write Java applications for zigzag star and number patterns in this part. Printing Zig Zag Number Pattern Steps Print one...

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

Java Program to Sort an Array of 0's, 1's, and 2’s | Dutch National Flag Problem in Java

The famed Dutch computer programmer Edsger Dijkstra's Dutch Nation Flag (DNF) challenge ranks among the most well-known programming challenges. The Dutch tricolor flag, comprising red, white, and blue, is the...

3 minutes read.

Java Math toIntExact() Method

The toIntExact() method of Java Math class returns the int value of the given long argument, throwing an exception if the value overflows an int. Syntax: public static int toIntExact (long value) Parameters: The...

2 minutes 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.

What is anagram in Java?

In this section will explain what an anagram is in Java and demonstrate how to determine whether or not a text is an anagram. In Java interviews, the anagram Java...

4 minutes read.

Perfect Number in Java

The concept of a perfect number in Java will be defined in this chapter, along with creating Program code that determine whether a specific number is perfect or not. Additionally,...

4 minutes read.