Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Tree
  • Practice Tree
  • MCQs on Tree
  • Tutorial on Tree
  • Types of Trees
  • Basic operations
  • Tree Traversal
  • Binary Tree
  • Complete Binary Tree
  • Ternary Tree
  • Binary Search Tree
  • Red-Black Tree
  • AVL Tree
  • Full Binary Tree
  • B-Tree
  • Advantages & Disadvantages
Open In App
Next Article:
Preorder Traversal of Binary Tree
Next article icon

Reverse Morris traversal using Threaded Binary Tree

Last Updated : 06 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a binary tree, the task is to perform reverse in-order traversal using Morris Traversal.

Example:

Input:

Iterative-Postorder-Traversal

Output: 3 1 5 2 4
Explanation: Inorder traversal (Right->Root->Left) of the tree is 3 1 5 2 4

Input:

Iterative-Postorder-Traversal-2

Output: 6 5 10 6 8 10 7 1
Explanation: Inorder traversal (Right->Root->Left) of the tree is 6 5 10 6 8 10 7 1

Morris (In-order) Traversal is a tree traversal algorithm that operates without recursion or a stack by creating temporary links in the tree, using them to traverse nodes, and then restoring the tree’s original structure.

Prerequisites : 

  • Morris Traversals 
  • Threaded Binary Trees: In a binary tree with n nodes, n + 1 NULL pointers waste memory. Threaded binary trees use these NULL pointers to store useful information.
    • Left-threaded: Stores ancestor information in NULL left pointers.
    • Right-threaded: Stores successor information in NULL right pointers.
    • Fully-threaded: Stores both predecessor (NULL left) and successor (NULL right) information.

Reverse Morris Traversal:

This is the inverse process of Morris Traversals , where links to the in-order descendants are created, used to traverse in reverse order, and then removed to restore the original structure.

Approach:  

  • Initialize Current as root.
  • While current is not NULL :
  • If current has no right child, visit the current node and move to the left child of current.
  • Else, find the in-order successor of current node. In-order successor is the left most node in the right subtree or right child itself.
    • If the left child of the in-order successor is NULL, set current as the left child of its in-order successor and move current node to its right.
    • Else, if the threaded link between the current and it’s in-order successor already exists, set left pointer of the in-order successor as NULL, visit Current node and move to its left child node.
C++
// C++ program to print reverse inorder  // traversal using morris traversal. #include <bits/stdc++.h> using namespace std;  class Node { public:     int data;     Node* left;     Node* right;     Node(int x) {         data = x;         left = nullptr;          right = nullptr;     } };  // Function to perform reverse // morris traversal. vector<int> reverseMorris(Node* root) {     vector<int> ans;      Node* curr = root;     while (curr != nullptr) {                  // if right child is null, append          // curr node and move to left node.         if (curr->right == nullptr) {             ans.push_back(curr->data);             curr = curr->left;         }         else {              // Find the inorder successor of curr             Node* succ = curr->right;             while (succ->left != nullptr                    && succ->left != curr)                 succ = succ->left;              // Make curr as the left child of its             // inorder successor and move to              // right node.             if (succ->left == nullptr) {                 succ->left = curr;                 curr = curr->right;             }              // Revert the changes made in the 'if' part to             // restore the original tree i.e., fix the left             // child of successor and move to left node.             else {                 succ->left = nullptr;                 ans.push_back(curr->data);                 curr = curr->left;             }         }     }          return ans; }  int main() {          // Constructed binary tree is     //           1     //         /   \     //        2     3     //      /  \   / \     //     4    5  6  7     Node *root = new Node(1);     root->left = new Node(2);     root->right = new Node(3);     root->left->left = new Node(4);     root->left->right = new Node(5);     root->right->left = new Node(6);     root->right->right = new Node(7);      vector<int> res = reverseMorris(root);     for (auto num: res) cout << num << " ";     cout << endl;     return 0; } 
Java
// Java program to print reverse inorder  // traversal using morris traversal.  import java.util.ArrayList; import java.util.List;  class Node {     int data;     Node left, right;      Node(int x) {         data = x;         left = null;         right = null;     } }  class GfG {      // Function to perform reverse     // morris traversal.     static List<Integer> reverseMorris(Node root) {         List<Integer> ans = new ArrayList<>();         Node curr = root;         while (curr != null) {                          // if right child is null, add              // curr node and move to left node.             if (curr.right == null) {                 ans.add(curr.data);                 curr = curr.left;             } else {                  // Find the inorder successor of curr                 Node succ = curr.right;                 while (succ.left != null && succ.left != curr) {                     succ = succ.left;                 }                  // Make curr as the left child of its                 // inorder successor and move to                  // right node.                 if (succ.left == null) {                     succ.left = curr;                     curr = curr.right;                 }                                  // Revert the changes made in the 'if' part to                 // restore the original tree i.e., fix the left                 // child of successor and move to left node.                 else {                     succ.left = null;                     ans.add(curr.data);                     curr = curr.left;                 }             }         }                  return ans;     }      public static void main(String[] args) {          // Constructed binary tree is         //           1         //         /   \         //        2     3         //      /  \   / \         //     4    5  6  7         Node root = new Node(1);         root.left = new Node(2);         root.right = new Node(3);         root.left.left = new Node(4);         root.left.right = new Node(5);         root.right.left = new Node(6);         root.right.right = new Node(7);          List<Integer> res = reverseMorris(root);         for (int num : res) {             System.out.print(num + " ");         }         System.out.println();     } } 
Python
# Python program to print reverse inorder  # traversal using morris traversal.  class Node:     def __init__(self, x):         self.data = x         self.left = None         self.right = None  # Function to perform reverse # morris traversal. def reverseMorris(root):     ans = []     curr = root     while curr is not None:                  # if right child is null, append          # curr node and move to left node.         if curr.right is None:             ans.append(curr.data)             curr = curr.left         else:              # Find the inorder successor of curr             succ = curr.right             while succ.left is not None and \             				succ.left != curr:                 succ = succ.left              # Make curr as the left child of its             # inorder successor and move to              # right node.             if succ.left is None:                 succ.left = curr                 curr = curr.right                              # Revert the changes made in the 'if' part to             # restore the original tree i.e., fix the left             # child of successor and move to left node.             else:                 succ.left = None                 ans.append(curr.data)                 curr = curr.left          return ans  if __name__ == "__main__":      # Constructed binary tree is     #           1     #         /   \     #        2     3     #      /  \   / \     #     4    5  6  7     root = Node(1)     root.left = Node(2)     root.right = Node(3)     root.left.left = Node(4)     root.left.right = Node(5)     root.right.left = Node(6)     root.right.right = Node(7)      res = reverseMorris(root)     print(" ".join(map(str, res))) 
C#
// C# program to print reverse inorder  // traversal using morris traversal.  using System; using System.Collections.Generic;  class Node {     public int data;     public Node left, right;      public Node(int x) {         data = x;         left = null;         right = null;     } }  class GfG {      // Function to perform reverse     // morris traversal.     static List<int> reverseMorris(Node root) {         List<int> ans = new List<int>();         Node curr = root;         while (curr != null) {                          // if right child is null, add              // curr node and move to left node.             if (curr.right == null) {                 ans.Add(curr.data);                 curr = curr.left;             } else {                  // Find the inorder successor of curr                 Node succ = curr.right;                 while (succ.left != null && succ.left != curr) {                     succ = succ.left;                 }                  // Make curr as the left child of its                 // inorder successor and move to                  // right node.                 if (succ.left == null) {                     succ.left = curr;                     curr = curr.right;                 }                                  // Revert the changes made in the 'if' part to                 // restore the original tree i.e., fix the left                 // child of successor and move to left node.                 else {                     succ.left = null;                     ans.Add(curr.data);                     curr = curr.left;                 }             }         }                  return ans;     }      static void Main(string[] args) {          // Constructed binary tree is         //           1         //         /   \         //        2     3         //      /  \   / \         //     4    5  6  7         Node root = new Node(1);         root.left = new Node(2);         root.right = new Node(3);         root.left.left = new Node(4);         root.left.right = new Node(5);         root.right.left = new Node(6);         root.right.right = new Node(7);          List<int> res = reverseMorris(root);         Console.WriteLine(string.Join(" ", res));     } } 
JavaScript
// JavaScript program to print reverse inorder  // traversal using morris traversal.  class Node {     constructor(x) {         this.data = x;         this.left = null;         this.right = null;     } }  // Function to perform reverse // morris traversal. function reverseMorris(root) {     const ans = [];     let curr = root;     while (curr !== null) {                  // if right child is null, add          // curr node and move to left node.         if (curr.right === null) {             ans.push(curr.data);             curr = curr.left;         } else {              // Find the inorder successor of curr             let succ = curr.right;             while (succ.left !== null && succ.left !== curr) {                 succ = succ.left;             }              // Make curr as the left child of its             // inorder successor and move to              // right node.             if (succ.left === null) {                 succ.left = curr;                 curr = curr.right;             }                          // Revert the changes made in the 'if' part to             // restore the original tree i.e., fix the left             // child of successor and move to left node.             else {                 succ.left = null;                 ans.push(curr.data);                 curr = curr.left;             }         }     }     return ans; }  // Constructed binary tree is //           1 //         /   \ //        2     3 //      /  \   / \ //     4    5  6  7 const root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.left = new Node(6); root.right.right = new Node(7);  const res = reverseMorris(root); console.log(res.join(" ")); 

Output
7 3 6 1 5 2 4 

Time Complexity : O(n), where n is the number of nodes in the tree. Each node will be traversed at most 3 times.
Auxiliary Space : O(1)



Next Article
Preorder Traversal of Binary Tree

A

AnishSinghWalia
Improve
Article Tags :
  • Advanced Data Structure
  • DSA
  • Tree
Practice Tags :
  • Advanced Data Structure
  • Tree

Similar Reads

  • Level order traversal of Binary Tree using Morris Traversal
    Given a binary tree, the task is to traverse the Binary Tree in level order fashion.Examples: Input: 1 / \ 2 3 Output: 1 2 3 Input: 5 / \ 2 3 \ 6 Output: 5 2 3 6 Approach: The idea is to use Morris Preorder Traversal to traverse the tree in level order traversal.Observations: There are mainly two ob
    11 min read
  • Reverse zigzag Traversal of a Binary Tree
    Given a Binary Tree, the task is to print the Reverse Zig-zag order of the tree. In Zig-zag traversal starting from the first level go from left to right for odd-numbered levels and right to left for even-numbered levels. For Reverse Zig-zag traversal just print the reverse of this traversal.Example
    10 min read
  • Reverse Clockwise spiral traversal of a binary tree
    Given a Binary Tree. The task is to print the circular reverse clockwise spiral order traversal of the given binary tree.Reverse Clockwise Traversal means to traverse the tree in clockwise direction spirally starting from the bottom instead of top root node.Examples: Input : 1 / \ 2 3 / \ \ 4 5 6 /
    11 min read
  • Preorder Traversal of Binary Tree
    Preorder traversal is a tree traversal method that follows the Root-Left-Right order: The root node of the subtree is visited first.Next, the left subtree is recursively traversed.Finally, the right subtree is recursively traversed.How does Preorder Traversal work?Key Properties: Used in expression
    5 min read
  • Binary Tree Iterator for Inorder Traversal
    Given a Binary Tree and an input array. The task is to create an Iterator that utilizes next() and hasNext() functions to perform Inorder traversal on the binary tree. Examples: Input: 8 Input Array = [next(), hasNext(), next(), next(), next(), hasNext(), next(), next(), hasNext()] / \ 3 9 / \ 2 4 \
    13 min read
  • Inorder Non-threaded Binary Tree Traversal without Recursion or Stack
    We have discussed Thread based Morris Traversal. Can we do inorder traversal without threads if we have parent pointers available to us? Input: Root of Below Tree [Every node of tree has parent pointer also] 10 / \ 5 100 / \ 80 120 Output: 5 10 80 100 120 The code should not extra space (No Recursio
    11 min read
  • Post Order Traversal of Binary Tree in O(N) using O(1) space
    Prerequisites:- Morris Inorder Traversal, Tree Traversals (Inorder, Preorder and Postorder)Given a Binary Tree, the task is to print the elements in post order using O(N) time complexity and constant space. Input: 1 / \ 2 3 / \ / \ 4 5 6 7 / \ 8 9Output: 8 9 4 5 2 6 7 3 1Input: 5 / \ 7 3 / \ / \ 4 1
    15+ min read
  • Postorder Traversal of Binary Tree
    Postorder traversal is a tree traversal method that follows the Left-Right-Root order: The left subtree is visited first.The right subtree is visited next.The root node is processed last.How does Postorder Traversal work? Key Properties:It is used for tree deletion because subtrees are deleted befor
    5 min read
  • Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue)
    We have discussed Threaded Binary Tree. The idea of threaded binary trees is to make inorder traversal faster and do it without stack and without recursion. In a simple threaded binary tree, the NULL right pointers are used to store inorder successor. Wherever a right pointer is NULL, it is used to
    12 min read
  • Mix Order Traversal of a Binary Tree
    Given a Binary Tree consisting of N nodes, the task is to print its Mix Order Traversal. Mix Order Traversal is a tree traversal technique, which involves any two of the existing traversal techniques like Inorder, Preorder and Postorder Traversal. Any two of them can be performed or alternate levels
    13 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences