The Wayback Machine - https://web.archive.org/web/20241001004754/https://www.geeksforgeeks.org/inorder-tree-traversal-without-recursion-and-without-stack/
Open In App

Inorder Tree Traversal without recursion and without stack!

Last Updated : 16 Jun, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
 

Using Morris Traversal, we can traverse the tree without using stack and recursion. The idea of Morris Traversal is based on Threaded Binary Tree. In this traversal, we first create links to Inorder successor and print the data using these links, and finally revert the changes to restore original tree. 

1. Initialize current as root 
2. While current is not NULL
   If the current does not have left child
      a) Print current’s data
      b) Go to the right, i.e., current = current->right
   Else
      a) Find rightmost node in current left subtree OR
              node whose right child == current.
         If we found right child == current
             a) Update the right child as NULL of that node whose right child is current
             b) Print current’s data
             c) Go to the right, i.e. current = current->right
         Else
             a) Make current as the right child of that rightmost 
                node we found; and 
             b) Go to this left child, i.e., current = current->left

Although the tree is modified through the traversal, it is reverted back to its original shape after the completion. Unlike Stack based traversal, no extra space is required for this traversal.

C++




#include <bits/stdc++.h>
using namespace std;
 
/* A binary tree tNode has data, a pointer to left child
   and a pointer to right child */
struct tNode {
    int data;
    struct tNode* left;
    struct tNode* right;
};
 
/* Function to traverse the binary tree without recursion
   and without stack */
void MorrisTraversal(struct tNode* root)
{
    struct tNode *current, *pre;
 
    if (root == NULL)
        return;
 
    current = root;
    while (current != NULL) {
 
        if (current->left == NULL) {
            cout << current->data << " ";
            current = current->right;
        }
        else {
 
            /* Find the inorder predecessor of current */
            pre = current->left;
            while (pre->right != NULL
                   && pre->right != current)
                pre = pre->right;
 
            /* Make current as the right child of its
               inorder predecessor */
            if (pre->right == NULL) {
                pre->right = current;
                current = current->left;
            }
 
            /* Revert the changes made in the 'if' part to
               restore the original tree i.e., fix the right
               child of predecessor */
            else {
                pre->right = NULL;
                cout << current->data << " ";
                current = current->right;
            } /* End of if condition pre->right == NULL */
        } /* End of if condition current->left == NULL*/
    } /* End of while */
}
 
/* UTILITY FUNCTIONS */
/* Helper function that allocates a new tNode with the
   given data and NULL left and right pointers. */
struct tNode* newtNode(int data)
{
    struct tNode* node = new tNode;
    node->data = data;
    node->left = NULL;
    node->right = NULL;
 
    return (node);
}
 
/* Driver program to test above functions*/
int main()
{
 
    /* Constructed binary tree is
            1
          /   \
         2     3
       /   \
      4     5
  */
    struct tNode* root = newtNode(1);
    root->left = newtNode(2);
    root->right = newtNode(3);
    root->left->left = newtNode(4);
    root->left->right = newtNode(5);
 
    MorrisTraversal(root);
 
    return 0;
}
 
// This code is contributed by Sania Kumari Gupta (kriSania804)


C




#include <stdio.h>
#include <stdlib.h>
 
/* A binary tree tNode has data, a pointer to left child
   and a pointer to right child */
typedef struct tNode {
    int data;
    struct tNode* left;
    struct tNode* right;
}tNode;
 
/* Function to traverse the binary tree without recursion
   and without stack */
void MorrisTraversal(tNode* root)
{
    tNode *current, *pre;
 
    if (root == NULL)
        return;
 
    current = root;
    while (current != NULL) {
 
        if (current->left == NULL) {
            printf("%d ", current->data);
            current = current->right;
        }
        else {
 
            /* Find the inorder predecessor of current */
            pre = current->left;
            while (pre->right != NULL
                   && pre->right != current)
                pre = pre->right;
 
            /* Make current as the right child of its
               inorder predecessor */
            if (pre->right == NULL) {
                pre->right = current;
                current = current->left;
            }
 
            /* Revert the changes made in the 'if' part to
               restore the original tree i.e., fix the right
               child of predecessor */
            else {
                pre->right = NULL;
                printf("%d ", current->data);
                current = current->right;
            } /* End of if condition pre->right == NULL */
        } /* End of if condition current->left == NULL*/
    } /* End of while */
}
 
/* UTILITY FUNCTIONS */
/* Helper function that allocates a new tNode with the
   given data and NULL left and right pointers. */
tNode* newtNode(int data)
{
    tNode* node = (tNode *)malloc(sizeof(tNode));
    node->data = data;
    node->left = NULL;
    node->right = NULL;
 
    return (node);
}
 
/* Driver program to test above functions*/
int main()
{
 
    /* Constructed binary tree is
            1
          /   \
         2     3
       /   \
      4     5
  */
    tNode* root = newtNode(1);
    root->left = newtNode(2);
    root->right = newtNode(3);
    root->left->left = newtNode(4);
    root->left->right = newtNode(5);
 
    MorrisTraversal(root);
 
    return 0;
}
 
// This code is contributed by Sania Kumari Gupta (kriSania804)


Java




// Java program to print inorder
// traversal without recursion
// and stack
 
/* A binary tree tNode has data,
   a pointer to left child
   and a pointer to right child */
class tNode {
    int data;
    tNode left, right;
 
    tNode(int item)
    {
        data = item;
        left = right = null;
    }
}
 
class BinaryTree {
    tNode root;
 
    /* Function to traverse a
       binary tree without recursion
       and without stack */
    void MorrisTraversal(tNode root)
    {
        tNode current, pre;
 
        if (root == null)
            return;
 
        current = root;
        while (current != null)
        {
            if (current.left == null)
            {
                System.out.print(current.data + " ");
                current = current.right;
            }
            else {
                /* Find the inorder
                    predecessor of current
                 */
                pre = current.left;
                while (pre.right != null
                       && pre.right != current)
                    pre = pre.right;
 
                /* Make current as right
                   child of its
                 * inorder predecessor */
                if (pre.right == null) {
                    pre.right = current;
                    current = current.left;
                }
 
                /* Revert the changes made
                   in the 'if' part
                   to restore the original
                   tree i.e., fix
                   the right child of predecessor*/
                else
                {
                    pre.right = null;
                    System.out.print(current.data + " ");
                    current = current.right;
                } /* End of if condition pre->right == NULL
                   */
 
            } /* End of if condition current->left == NULL*/
 
        } /* End of while */
    }
 
    // Driver Code
    public static void main(String args[])
    {
        /* Constructed binary tree is
               1
             /   \
            2      3
          /   \
         4     5
        */
        BinaryTree tree = new BinaryTree();
        tree.root = new tNode(1);
        tree.root.left = new tNode(2);
        tree.root.right = new tNode(3);
        tree.root.left.left = new tNode(4);
        tree.root.left.right = new tNode(5);
 
        tree.MorrisTraversal(tree.root);
    }
}
 
// This code has been contributed by Mayank
// Jaiswal(mayank_24)


Python3




class TreeNode:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
 
def morris_traversal(root):
    current = root
 
    while current:
        if current.left is None:
            print(current.data, end=" ")
            current = current.right
        else:
            # Find the inorder predecessor of current
            pre = current.left
            while pre.right and pre.right != current:
                pre = pre.right
 
            # Make current as the right child of its inorder predecessor
            if pre.right is None:
                pre.right = current
                current = current.left
            # Revert the changes made to restore the original tree and print current node
            else:
                pre.right = None
                print(current.data, end=" ")
                current = current.right
 
# Driver program to test above functions
if __name__ == '__main__':
    """
    Constructed binary tree is
            1
          /   \
         2     3
       /   \
      4     5
    """
    root = TreeNode(1)
    root.left = TreeNode(2)
    root.right = TreeNode(3)
    root.left.left = TreeNode(4)
    root.left.right = TreeNode(5)
 
    morris_traversal(root)


C#




// C# program to print inorder traversal
// without recursion and stack
using System;
 
/* A binary tree tNode has data,
    pointer to left child
    and a pointer to right child */
 
class BinaryTree {
    tNode root;
 
    public class tNode {
        public int data;
        public tNode left, right;
 
        public tNode(int item)
        {
            data = item;
            left = right = null;
        }
    }
    /* Function to traverse binary tree without
     recursion and without stack */
    void MorrisTraversal(tNode root)
    {
        tNode current, pre;
 
        if (root == null)
            return;
 
        current = root;
        while (current != null)
        {
            if (current.left == null)
            {
                Console.Write(current.data + " ");
                current = current.right;
            }
            else {
                /* Find the inorder
                    predecessor of current
                 */
                pre = current.left;
                while (pre.right != null
                       && pre.right != current)
                    pre = pre.right;
 
                /* Make current as right child
                of its inorder predecessor */
                if (pre.right == null)
                {
                    pre.right = current;
                    current = current.left;
                }
 
                /* Revert the changes made in
                if part to restore the original
                tree i.e., fix the right child
                of predecessor*/
                else
                {
                    pre.right = null;
                    Console.Write(current.data + " ");
                    current = current.right;
                } /* End of if condition pre->right == NULL
                   */
 
            } /* End of if condition current->left == NULL*/
 
        } /* End of while */
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        /* Constructed binary tree is
            1
            / \
            2     3
        / \
        4     5
        */
        BinaryTree tree = new BinaryTree();
        tree.root = new tNode(1);
        tree.root.left = new tNode(2);
        tree.root.right = new tNode(3);
        tree.root.left.left = new tNode(4);
        tree.root.left.right = new tNode(5);
 
        tree.MorrisTraversal(tree.root);
    }
}
 
// This code has been contributed
// by Arnab Kundu


Javascript




<script>
 
// JavaScript program to print inorder
// traversal without recursion
// and stack
  
/* A binary tree tNode has data,
   a pointer to left child
   and a pointer to right child */
class tNode
{
    constructor(item)
    {
        this.data = item;
        this.left = this.right = null;
    }
}
 
let root;
 
/* Function to traverse a
       binary tree without recursion
       and without stack */
function MorrisTraversal(root)
{
    let current, pre;
  
        if (root == null)
            return;
  
        current = root;
        while (current != null)
        {
            if (current.left == null)
            {
                document.write(current.data + " ");
                current = current.right;
            }
            else {
                /* Find the inorder
                    predecessor of current
                 */
                pre = current.left;
                while (pre.right != null
                       && pre.right != current)
                    pre = pre.right;
  
                /* Make current as right
                   child of its
                 * inorder predecessor */
                if (pre.right == null) {
                    pre.right = current;
                    current = current.left;
                }
  
                /* Revert the changes made
                   in the 'if' part
                   to restore the original
                   tree i.e., fix
                   the right child of predecessor*/
                else
                {
                    pre.right = null;
                    document.write(current.data + " ");
                    current = current.right;
                } /* End of if condition pre->right == NULL
                   */
  
            } /* End of if condition current->left == NULL*/
  
        } /* End of while */
}
 
// Driver Code
/* Constructed binary tree is
               1
             /   \
            2      3
          /   \
         4     5
        */
 
root = new tNode(1);
root.left = new tNode(2);
root.right = new tNode(3);
root.left.left = new tNode(4);
root.left.right = new tNode(5);
 
MorrisTraversal(root);
 
// This code is contributed by avanitrachhadiya2155
 
</script>


Output

4 2 5 1 3 

Time Complexity: O(n) If we take a closer look, we can notice that every edge of the tree is traversed at most three times. And in the worst case, the same number of extra edges (as input tree) are created and removed.
Auxiliary Space: O(1) since using only constant variables

References: 
www.liacs.nl/~deutz/DS/september28.pdf 
www.scss.tcd.ie/disciplines/software_systems/…/HughGibbonsSlides.pdf
Please write comments if you find any bug in above code/algorithm, or want to share more information about stack Morris Inorder Tree Traversal.
 



Similar Reads

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 Recursion and stack) In inorder traversal, we follow "left
11 min read
Inorder Tree Traversal without Recursion
In this post, we have seen in detail about the Inorder traversal and how it is implemented using recursion. Here in this post, we will discuss methods to implement inorder traversal without using recursion. Inorder Traversal using Stack:As we already know, recursion can also be implemented using stack. Here also we can use a stack to perform inorde
15+ min read
Postorder traversal of Binary Tree without recursion and without stack
Given a binary tree, perform postorder traversal. Prerequisite - Inorder/preorder/postorder traversal of tree We have discussed the below methods for postorder traversal. 1) Recursive Postorder Traversal. 2) Postorder traversal using Stack. 2) Postorder traversal using two Stacks. Approach 1 The approach used is based on using an unordered set to k
15 min read
Preorder, Postorder and Inorder Traversal of a Binary Tree using a single Stack
Given a binary tree, the task is to print all the nodes of the binary tree in Pre-order, Post-order, and In-order iteratively using only one stack traversal. Examples: Input: Output:Preorder Traversal: 1 2 3Inorder Traversal: 2 1 3Postorder Traversal: 2 3 1 Input: Output:Preorder traversal: 1 2 4 5 3 6 7Inorder traversal: 4 2 5 1 6 3 7Post-order tr
13 min read
Pre Order, Post Order and In Order traversal of a Binary Tree in one traversal | (Using recursion)
Given a binary tree, the task is to print all the nodes of the binary tree in Pre-order, Post-order, and In-order in one iteration. Examples: Input: Output: Pre Order: 1 2 4 5 3 6 7 Post Order: 4 5 2 6 7 3 1 In Order: 4 2 5 1 6 3 7 Input: Output: Pre Order: 1 2 4 8 12 5 9 3 6 7 10 11 Post Order: 12 8 4 9 5 2 6 10 11 7 3 1 In Order: 8 12 4 2 9 5 1 6
9 min read
Cartesian tree from inorder traversal | Segment Tree
Given an in-order traversal of a cartesian tree, the task is to build the entire tree from it. Examples: Input: arr[] = {1, 5, 3} Output: 1 5 3 5 / \ 1 3 Input: arr[] = {3, 7, 4, 8} Output: 3 7 4 8 8 / 7 / \ 3 4 Approach: We have already seen an algorithm here that takes O(NlogN) time on an average but can get to O(N2) in the worst case.In this art
13 min read
Calculate height of Binary Tree using Inorder and Level Order Traversal
Given inorder traversal and Level Order traversal of a Binary Tree. The task is to calculate the height of the tree without constructing it. Example: Input : Input: Two arrays that represent Inorder and level order traversals of a Binary Tree in[] = {4, 8, 10, 12, 14, 20, 22}; level[] = {20, 8, 22, 4, 12, 10, 14}; Output : 4 The binary tree that ca
12 min read
Check if given inorder and preorder traversals are valid for any Binary Tree without building the tree
cGiven two arrays pre[] and in[] representing the preorder and inorder traversal of the binary tree, the task is to check if the given traversals are valid for any binary tree or not without building the tree. If it is possible, then print Yes. Otherwise, print No. Examples: Input: pre[] = {1, 2, 4, 5, 7, 3, 6, 8}, in[] = {4, 2, 5, 7, 1, 6, 8, 3}Ou
15+ min read
Preorder Traversal of N-ary Tree Without Recursion
Given an n-ary tree, print preorder traversal of it. Example : Preorder traversal of below tree is A B K N M J F D G E C H I L The idea is to use stack like iterative preorder traversal of binary tree. Create an empty stack to store nodes. Push the root node to the stack. Run a loop while the stack is not empty Pop the top node from stack. Print th
7 min read
Construct Special Binary Tree from given Inorder traversal
Given Inorder Traversal of a Special Binary Tree in which the key of every node is greater than keys in left and right children, construct the Binary Tree and return root. Examples: Input: inorder[] = {5, 10, 40, 30, 28} Output: root of following tree 40 / \ 10 30 / \ 5 28 Input: inorder[] = {1, 5, 10, 40, 30, 15, 28, 20} Output: root of following
14 min read
Check if Inorder traversal of a Binary Tree is palindrome or not
Given a binary tree and the task if to check if its Inorder Sequence is a palindrome or not. Examples: Input: Output: True Explanation: The Inorder sequence of the tree is "bbaaabb" which is a palindromic string.Input: Output: False Explanation: The Inorder sequence of the tree is "bbdaabb" which is not a palindromic string. Approach: To solve the
8 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 \ 5 Output: [2, true, 3, 4, 5, true, 8, 9, false] E
13 min read
Inorder traversal of an N-ary Tree
Given an N-ary tree containing, the task is to print the inorder traversal of the tree. Examples:  Input: N = 3   Output: 5 6 2 7 3 1 4Input: N = 3   Output: 2 3 5 1 4 6  Approach: The inorder traversal of an N-ary tree is defined as visiting all the children except the last then the root and finally the last child recursively.  Recursively visit t
6 min read
Convert Binary Tree to Doubly Linked List using inorder traversal
Given a Binary Tree (BT), the task is to convert it to a Doubly Linked List (DLL) in place. The left and right pointers in nodes will be used as previous and next pointers respectively in converted DLL. The order of nodes in DLL must be the same as the order of the given Binary Tree. The first node of Inorder traversal (leftmost node in BT) must be
15+ min read
Inorder Traversal of Binary Tree
Inorder traversal is defined as a type of tree traversal technique which follows the Left-Root-Right pattern, such that: The left subtree is traversed firstThen the root node for that subtree is traversedFinally, the right subtree is traversed Examples of Inorder TraversalInput : .......A ............../ .......\ ...........B ...........COutput : B
7 min read
Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror tree
Given two arrays that represent Preorder traversals of a full binary tree and its mirror tree, we need to write a program to construct the binary tree using these two Preorder traversals.A Full Binary Tree is a binary tree where every node has either 0 or 2 children. Note: It is not possible to construct a general binary tree using these two traver
12 min read
Find maximum and minimum element in binary tree without using recursion or stack or queue
Given a binary tree. The task is to find out the maximum and minimum element in a binary tree without using recursion or stack or queue i.e, space complexity should be O(1). Examples: Input : 12 / \ 13 10 / \ 14 15 / \ / \ 21 24 22 23 Output : Max element : 24 Min element : 10 Input : 12 / \ 19 82 / / \ 41 15 95 \ / / \ 2 21 7 16 Output : Max eleme
10 min read
Print Postorder traversal from given Inorder and Preorder traversals
AuxiliaryGiven Inorder and Preorder traversals of a binary tree, print Postorder traversal. Example: Input: Inorder traversal in[] = {4, 2, 5, 1, 3, 6} Preorder traversal pre[] = {1, 2, 4, 5, 3, 6} Output: Postorder traversal is {4, 5, 2, 6, 3, 1} Traversals in the above example represents following tree 1 / \ 2 3 / \ \ 4 5 6Recommended PracticePos
15+ min read
Find n-th node of inorder traversal
Given the binary tree and you have to find out the n-th node of inorder traversal. Examples: Input : n = 4 10 / \ 20 30 / \ 40 50 Output : 10 Inorder Traversal is : 40 20 50 10 30 Input : n = 3 7 / \ 2 3 / \ 8 5 Output : 8 Inorder: 2 7 8 3 5 3th node is 8 We do simple Inorder Traversal. While doing the traversal, we keep track of the count of nodes
8 min read
Find all possible Binary Trees with given Inorder Traversal
Given an array that represents Inorder Traversal, the task is to find all possible Binary Trees with the given inorder traversal and print their preorder traversals. Examples: Input: inorder[] = {7, 5}Output: 5 77 5 Input: inorder[] = {1, 2, 3}Output: 1 2 31 3 22 1 33 1 23 2 1 Approach: The idea is to generate all possible binary trees that can be
8 min read
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 observations for the traversal of the tree using Mor
11 min read
Why is Tail Recursion optimization faster than normal Recursion?
What is tail recursion? Tail recursion is defined as a recursive function in which the recursive call is the last statement that is executed by the function. So basically nothing is left to execute after the recursion call. What is non-tail recursion? Non-tail or head recursion is defined as a recursive function in which the recursive call is the f
4 min read
Find maximum in stack in O(1) without using additional stack in Python
The task is to design a stack which can get the maximum value in the stack in O(1) time without using an additional stack in Python. Examples: Input: Consider the following SpecialStack 16 –> TOP29151918When getMax() is called it should return 29, which is the maximum element in the current stack. If we do pop two times on stack, the stack becom
3 min read
Construct a tree from Inorder and Level order traversals | Set 1
Given inorder and level-order traversals of a Binary Tree, construct the Binary Tree. Following is an example to illustrate the problem. Input: Two arrays that represent Inorder and level order traversals of a Binary Tree in[] = {4, 8, 10, 12, 14, 20, 22}; level[] = {20, 8, 22, 4, 12, 10, 14}; Output: Construct the tree represented by the two array
11 min read
Construct a tree from Inorder and Level order traversals | Set 2
Given inorder and level-order traversals of a Binary Tree, construct the Binary Tree. Following is an example to illustrate the problem. Examples: Input: Two arrays that represent Inorder and level order traversals of a Binary Tree in[] = {4, 8, 10, 12, 14, 20, 22}; level[] = {20, 8, 22, 4, 12, 10, 14}; Output: Construct the tree represented by the
15+ min read
Construct a Binary Tree from Postorder and Inorder
Given Postorder and Inorder traversals, construct the tree. Examples: Input: in[] = {2, 1, 3}post[] = {2, 3, 1} Output: Root of below tree 1 / \ 2 3 Input: in[] = {4, 8, 2, 5, 1, 6, 3, 7}post[] = {8, 4, 5, 2, 6, 7, 3, 1} Output: Root of below tree 1 / \ 2 3 / \ / \4 5 6 7 \ 8 Recommended PracticeTree from Postorder and InorderTry It! Approach: To s
15+ min read
Replace each node in binary tree with the sum of its inorder predecessor and successor
Given a binary tree containing n nodes. The problem is to replace each node in the binary tree with the sum of its inorder predecessor and inorder successor. Examples: Input : 1 / \ 2 3 / \ / \ 4 5 6 7 Output : 11 / \ 9 13 / \ / \ 2 3 4 3 For 1: Inorder predecessor = 5 Inorder successor = 6 Sum = 11 For 4: Inorder predecessor = 0 (as inorder predec
15+ min read
Check if given Preorder, Inorder and Postorder traversals are of same tree
Given Preorder, Inorder, and Postorder traversals of some tree. Write a program to check if they all are of the same tree. Examples: Input: Inorder -> 4 2 5 1 3 Preorder -> 1 2 4 5 3 Postorder -> 4 5 2 3 1Output: YesExplanation: All of the above three traversals are of the same tree 1 / \ 2 3 / \ 4 5Input: Inorder -> 4 2 5 1 3 Preorder
15+ min read
Construct Tree from given Inorder and Preorder traversals
Let us consider the below traversals: Inorder sequence: D B E A F C Preorder sequence: A B D E C FIn a Preorder sequence, the leftmost element is the root of the tree. So we know 'A' is the root for given sequences. By searching ‘A’ in the Inorder sequence, we can find out all elements on the left side of 'A' is in the left subtree and elements on
15+ min read
Print ancestors of a given binary tree node without recursion
Given a Binary Tree and a key, write a function that prints all the ancestors of the key in the given binary tree.For example, consider the following Binary Tree 1 / \ 2 3 / \ / \ 4 5 6 7 / \ / 8 9 10 Following are different input keys and their ancestors in the above tree Input Key List of Ancestors ------------------------- 1 2 1 3 1 4 2 1 5 2 1
15 min read
Practice Tags :