Reverse Morris traversal using Threaded Binary Tree

What is Morris traversal?
Morris (InOrder) Traversal is a tree traversal algorithm that does not use recursion or stacks. This traversal creates links as descendants and outputs nodes using those links. Finally, undo the changes to restore the original tree.
Given a binary tree, task is to do reverse inorder traversal using Morris Traversal.
Â
Prerequisites :Â
In a binary tree with n nodes, there are n + 1 NULL pointers which waste memory. So, threaded binary trees makes use of these NULL pointers to save lots of Memory.Â
So, in Threaded Binary trees these NULL pointers will store some useful information.
- Ancestor information is stored only in left NULL pointers, called left branching binary trees.
- Storing successor information in NULL right pointers only, called as right threaded binary trees.
- Storing predecessor information in NULL left pointers and successor information in NULL right pointers, called as fully threaded binary trees or simply threaded binary trees.
Morris traversal can be used to do Inorder traversal, reverse Inorder traversal, Pre-order traversal with constant extra memory consumed O(1).Â
Reverse Morris Traversal : It is the inverse of Morris Traversal. In reverse morris traversal, we first create links to the inorder descendants of the current node, use those links to output data, and finally undo the changes to restore the original tree, then reverse inorder traversal to hold.
Algorithm :Â Â
1) Initialize Current as root.
2) While current is not NULL :
2.1) If current has no right child
a) Visit the current node.
b) Move to the left child of current.
2.2) Else, here we have 2 cases:
a) Find the inorder successor of current node.
Inorder successor is the left most node
in the right subtree or right child itself.
b) If the left child of the inorder successor is NULL:
1) Set current as the left child of its inorder successor.
2) Move current node to its right.
c) Else, if the threaded link between the current node
and it's inorder successor already exists :
1) Set left pointer of the inorder successor as NULL.
2) Visit Current node.
3) Move current to it's left child.
Implementation:
C++
// CPP code for reverse Morris Traversal#include<bits/stdc++.h>Â
using namespace std;Â
// Node structurestruct Node {Â Â Â Â int data;Â Â Â Â Node *left, *right;};Â
// helper function to create a new nodeNode *newNode(int data){Â Â Â Â Node *temp = new Node;Â Â Â Â Â Â Â Â Â temp->data = data;Â Â Â Â temp->right = temp->left = NULL;Â
    return temp;}Â
// function for reverse inorder traversalvoid MorrisReverseInorder(Node *root){         if(!root)         return ;         // Auxiliary node pointers    Node *curr, *successor;         // initialize current as root    curr = root;         while(curr)    {        // case-1, if curr has no right child then         // visit current and move to left child        if(curr -> right == NULL)        {            cout << curr->data << " ";            curr = curr->left;        }                 // case-2        else        {            // find the inorder successor of            // current node i.e left most node in             // right subtree or right child itself            successor = curr->right;                         // finding left most in right subtree            while(successor->left != NULL &&                   successor->left != curr)                    successor = successor->left;                             // if the left of inorder successor is NULL            if(successor->left == NULL)            {                // then connect left link to current node                successor->left = curr;                                 // move current to right child                curr = curr->right;            }                         // otherwise inorder successor's left is            // not NULL and already left is linked             // with current node            else            {                successor->left = NULL;                                 // visiting the current node                cout << curr->data << " ";Â
                // move current to its left child                 curr = curr->left;            }        }    }}Â
// Driver codeint main(){Â
/* Constructed binary tree is          1        /  \       2    3     / \  / \    4   5 6   7*/Â
Node *root = newNode(1);root->left = newNode(2);root->right = newNode(3);root->left->left = newNode(4);root->left->right = newNode(5);root->right->left = newNode(6);root->right->right = newNode(7);Â
//reverse inorder traversal.MorrisReverseInorder(root);Â
return 0;} |
Java
// Java code for reverse Morris Traversalclass GFG{Â
// Node structurestatic class Node{Â Â Â Â int data;Â Â Â Â Node left, right;};Â
// helper function to create a new nodestatic Node newNode(int data){Â Â Â Â Node temp = new Node();Â Â Â Â Â Â Â Â Â temp.data = data;Â Â Â Â temp.right = temp.left = null;Â
    return temp;}Â
// function for reverse inorder traversalstatic void MorrisReverseInorder(Node root){         if(root == null)         return ;         // Auxiliary node pointers    Node curr, successor;         // initialize current as root    curr = root;         while(curr != null)    {        // case-1, if curr has no right child then         // visit current and move to left child        if(curr . right == null)        {                System.out.print( curr.data + " ");            curr = curr.left;        }                 // case-2        else        {            // find the inorder successor of            // current node i.e left most node in             // right subtree or right child itself            successor = curr.right;                         // finding left most in right subtree            while(successor.left != null &&                 successor.left != curr)                    successor = successor.left;                             // if the left of inorder successor is null            if(successor.left == null)            {                // then connect left link to current node                successor.left = curr;                                 // move current to right child                curr = curr.right;            }                         // otherwise inorder successor's left is            // not null and already left is linked             // with current node            else            {                successor.left = null;                                 // visiting the current node                System.out.print( curr.data + " ");Â
                // move current to its left child                 curr = curr.left;            }        }    }}Â
// Driver codepublic static void main(String args[]){Â
/* Constructed binary tree is        1        / \    2    3    / \ / \    4 5 6 7*/Â
Node root = newNode(1);root.left = newNode(2);root.right = newNode(3);root.left.left = newNode(4);root.left.right = newNode(5);root.right.left = newNode(6);root.right.right = newNode(7);Â
// reverse inorder traversal.MorrisReverseInorder(root);}}Â
// This code is contributed by Arnab Kundu |
Python3
# Python3 for reverse Morris TraversalÂ
# Utility function to create a new # tree node class newNode:    def __init__(self,data):        self.data = data        self.left = self.right = NoneÂ
# function for reverse inorder traversal def MorrisReverseInorder(root):Â
    if( not root) :        return             # initialize current as root     curr = root    successor = 0         while(curr):              # case-1, if curr has no right child then         # visit current and move to left child         if(curr.right == None) :                     print(curr.data, end = " ")             curr = curr.left                  # case-2         else:                     # find the inorder successor of             # current node i.e left most node in             # right subtree or right child itself             successor = curr.right                          # finding left most in right subtree             while(successor.left != None and                  successor.left != curr):                successor = successor.left                              # if the left of inorder successor is None             if(successor.left == None) :                             # then connect left link to current node                 successor.left = curr                                  # move current to right child                 curr = curr.right                          # otherwise inorder successor's left is             # not None and already left is linked             # with current node             else:                             successor.left = None                                 # visiting the current node                 print(curr.data, end = " " )Â
                # move current to its left child                 curr = curr.left Â
# Driver code if __name__ =="__main__":    """ Constructed binary tree is         1         / \     2    3     / \ / \     4 5 6 7 """Â
    root = newNode(1)     root.left = newNode(2)     root.right = newNode(3)     root.left.left = newNode(4)     root.left.right = newNode(5)     root.right.left = newNode(6)     root.right.right = newNode(7) Â
    #reverse inorder traversal.     MorrisReverseInorder(root)Â
# This code is contributed by# Shubham Singh(SHUBHAMSINGH10) |
C#
// C# code for reverse Morris Traversal using System;Â
class GFG { Â
// Node structure public class Node { Â Â Â Â public int data; Â Â Â Â public Node left, right; }; Â
// helper function to create a new node static Node newNode(int data) { Â Â Â Â Node temp = new Node(); Â Â Â Â Â Â Â Â Â temp.data = data; Â Â Â Â temp.right = temp.left = null; Â
    return temp; } Â
// function for reverse inorder traversal static void MorrisReverseInorder(Node root) {          if(root == null)         return ;          // Auxiliary node pointers     Node curr, successor;          // initialize current as root     curr = root;          while(curr != null)     {         // case-1, if curr has no right child then         // visit current and move to left child         if(curr . right == null)         {                 Console.Write( curr.data + " ");             curr = curr.left;         }                  // case-2         else        {             // find the inorder successor of             // current node i.e left most node in             // right subtree or right child itself             successor = curr.right;                          // finding left most in right subtree             while(successor.left != null &&                 successor.left != curr)                     successor = successor.left;                              // if the left of inorder successor is null             if(successor.left == null)             {                 // then connect left link to current node                 successor.left = curr;                                  // move current to right child                 curr = curr.right;             }                          // otherwise inorder successor's left is             // not null and already left is linked             // with current node             else            {                 successor.left = null;                                  // visiting the current node                 Console.Write( curr.data + " "); Â
                // move current to its left child                 curr = curr.left;             }         }     } } Â
// Driver code public static void Main(String []args) { Â
/* Constructed binary tree is         1         / \     2 3     / \ / \     4 5 6 7 */Â
Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.left = newNode(6); root.right.right = newNode(7); Â
// reverse inorder traversal. MorrisReverseInorder(root); } } Â
// This code contributed by Rajput-Ji |
Javascript
<script>Â
// Javascript code for reverse Morris Traversal Â
// Node structure class Node { Â Â Â Â constructor()Â Â Â Â {Â Â Â Â Â Â Â Â this.data = 0;Â Â Â Â Â Â Â Â this.left = null;Â Â Â Â Â Â Â Â this.right = null;Â Â Â Â }}; Â
// Helper function to create a new node function newNode(data) {     var temp = new Node();          temp.data = data;     temp.right = temp.left = null; Â
    return temp; } Â
// Function for reverse inorder traversal function MorrisReverseInorder(root) {     if (root == null)         return;              // Auxiliary node pointers     var curr, successor;          // Initialize current as root     curr = root;          while (curr != null)     {                  // case-1, if curr has no right child then         // visit current and move to left child         if (curr . right == null)         {             document.write( curr.data + " ");             curr = curr.left;         }                  // case-2         else        {                          // Find the inorder successor of             // current node i.e left most node in             // right subtree or right child itself             successor = curr.right;                          // Finding left most in right subtree             while(successor.left != null &&                   successor.left != curr)                 successor = successor.left;                              // If the left of inorder successor is null             if (successor.left == null)             {                                  // Then connect left link to current node                 successor.left = curr;                                  // Move current to right child                 curr = curr.right;             }                          // Otherwise inorder successor's left is             // not null and already left is linked             // with current node             else            {                 successor.left = null;                                  // Visiting the current node                 document.write( curr.data + " "); Â
                // Move current to its left child                 curr = curr.left;             }         }     } } Â
// Driver code /* Constructed binary tree is          1         / \        2  3       / \ / \      4 5 6 7 */var root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.left = newNode(6); root.right.right = newNode(7); Â
// Reverse inorder traversal. MorrisReverseInorder(root); Â
// This code is contributed by rrrtnxÂ
</script> |
7 3 6 1 5 2 4
Time Complexity : O(n)Â
Auxiliary Space : O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!




