Inorder Tree Traversal without Recursion Last Updated : 06 Nov, 2024 Comments Improve Suggest changes Like Article Like Report Try it on GfG Practice Given a binary tree, the task is to perform in-order traversal of the tree without using recursion.Example:Input:Output: 4 2 5 1 3Explanation: Inorder traversal (Left->Root->Right) of the tree is 4 2 5 1 3Input:Output: 1 7 10 8 6 10 5 6Explanation: Inorder traversal (Left->Root->Right) of the tree is 1 7 10 8 6 10 5 6Table of Content[Naive Approach] Using Stack - O(n) Time and O(h) Space[Expected Approach] Using Morris Traversal Algorithm - O(n) Time and O(1) Space[Naive Approach] Using Stack - O(n) Time and O(h) SpaceThe idea is to implement recursion using a stack to perform in-order traversal. Starting from root node, keep on pushing the node into a stack and move to left node. When node becomes null, pop a node from the stack, print its value and move to the right node.Illustration:Let us consider the below tree for example:Initially Creates an empty stack: S = NULL and set current as address of root: current -> 1Starting at Root (Node 1): current = 1Push 1 to the stack. Stack S = [1]Move current to the left child: current = 2At Node 2:Push 2 to the stack. Stack S = [2, 1]Move current to the left child: current = 4At Node 4:Push 4 to the stack. Stack S = [4, 2, 1]Move current to the left child: current = NULL (Node 4 has no left child)current is NULL:Pop 4 from the stack. Stack S = [2, 1]Print 4Move current to the right child of Node 4: current = NULL (Node 4 has no right child)Repeat with current = NULL:Pop 2 from the stack. Stack S = [1]Print 2Move current to the right child of Node 2: current = 5At Node 5:Push 5 to the stack. Stack S = [5, 1]Move current to the left child: current = NULL (Node 5 has no left child)current is NULL:Pop 5 from the stack. Stack S = [1]Print 5Move current to the right child of Node 5: current = NULL (Node 5 has no right child)Repeat with current = NULL:Pop 1 from the stack. Stack S = []Print 1Move current to the right child of Node 1: current = 3At Node 3:Push 3 to the stack. Stack S = [3]Move current to the left child: current = NULL (Node 3 has no left child)current is NULL:Pop 3 from the stack. Stack S = []Print 3Move current to the right child of Node 3: current = NULL (Node 3 has no right child) C++ // C++ program to print inorder traversal // using stack. #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; } }; //Iterative function for inorder tree traversal vector<int> inOrder(Node* root) { vector<int> ans; stack<Node*> s; Node* curr = root; while (curr != nullptr || s.empty() == false) { // Reach the left most Node of the // curr Node while (curr != nullptr) { // Place pointer to a tree node on // the stack before traversing // the node's left subtree s.push(curr); curr = curr->left; } // Current must be NULL at this point curr = s.top(); s.pop(); ans.push_back(curr->data); // we have visited the node and its // left subtree. Now, it's right // subtree's turn curr = curr->right; } return ans; } int main() { // Constructed binary tree is // 1 // / \ // 2 3 // / \ // 4 5 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); vector<int> res = inOrder(root); for (int i = 0; i < res.size(); i++) { cout << res[i] << " "; } } Java // Java program to print inorder traversal // using stack. import java.util.ArrayList; import java.util.Stack; class Node { int data; Node left, right; Node(int x) { data = x; left = null; right = null; } } class GfG { // Iterative function for inorder tree traversal static ArrayList<Integer> inOrder(Node root) { ArrayList<Integer> ans = new ArrayList<>(); Stack<Node> s = new Stack<>(); Node curr = root; while (curr != null || !s.isEmpty()) { // Reach the left most Node of the curr Node while (curr != null) { // Place pointer to a tree node on // the stack before traversing // the node's left subtree s.push(curr); curr = curr.left; } // Current must be NULL at this point curr = s.pop(); ans.add(curr.data); // we have visited the node and its // left subtree. Now, it's right // subtree's turn curr = curr.right; } return ans; } static void printList(ArrayList<Integer> v) { for (int i : v) { System.out.print(i + " "); } System.out.println(); } public static void main(String[] args) { // Constructed binary tree is // 1 // / \ // 2 3 // / \ // 4 5 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); ArrayList<Integer> res = inOrder(root); printList(res); } } Python # Python program to print inorder traversal # using stack. class Node: def __init__(self, x): self.data = x self.left = None self.right = None # Iterative function for inorder # tree traversal def inOrder(root): ans = [] stack = [] curr = root while curr is not None or len(stack) > 0: # Reach the left most Node of the curr Node while curr is not None: # Place pointer to a tree node on # the stack before traversing # the node's left subtree stack.append(curr) curr = curr.left # Current must be None at this point curr = stack.pop() ans.append(curr.data) # we have visited the node and its # left subtree. Now, it's right # subtree's turn curr = curr.right return ans def printList(v): print(" ".join(map(str, v))) if __name__ == "__main__": # Constructed binary tree is # 1 # / \ # 2 3 # / \ # 4 5 root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) res = inOrder(root) printList(res) C# // C# program to print inorder traversal // using stack. 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 { // Iterative function for inorder tree traversal static List<int> InOrder(Node root) { List<int> ans = new List<int>(); Stack<Node> s = new Stack<Node>(); Node curr = root; while (curr != null || s.Count > 0) { // Reach the left most Node of the curr Node while (curr != null) { // Place pointer to a tree node on // the stack before traversing // the node's left subtree s.Push(curr); curr = curr.left; } // Current must be NULL at this point curr = s.Pop(); ans.Add(curr.data); // we have visited the node and its // left subtree. Now, it's right // subtree's turn curr = curr.right; } return ans; } static void PrintList(List<int> v) { foreach (int i in v) { Console.Write(i + " "); } Console.WriteLine(); } static void Main(string[] args) { // Constructed binary tree is // 1 // / \ // 2 3 // / \ // 4 5 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); List<int> res = InOrder(root); PrintList(res); } } JavaScript // JavaScript program to print inorder traversal // using stack. class Node { constructor(x) { this.data = x; this.left = null; this.right = null; } } // Iterative function for inorder tree traversal function inOrder(root) { let ans = []; let s = []; let curr = root; while (curr !== null || s.length > 0) { // Reach the left most Node of the curr Node while (curr !== null) { // Place pointer to a tree node on // the stack before traversing // the node's left subtree s.push(curr); curr = curr.left; } // Current must be NULL at this point curr = s.pop(); ans.push(curr.data); // we have visited the node and its // left subtree. Now, it's right // subtree's turn curr = curr.right; } return ans; } function printList(v) { console.log(v.join(" ")); } // Constructed binary tree is // 1 // / \ // 2 3 // / \ // 4 5 let 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); let res = inOrder(root); printList(res); Output4 2 5 1 3 [Expected Approach] Using Morris Traversal Algorithm - O(n) Time and O(1) SpaceUsing 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. Please Refer to Inorder Tree Traversal without recursion and without stack! for implementation. Comment More infoAdvertise with us Next Article Types of Trees in Data Structures kartik Follow Improve Article Tags : Tree Stack DSA tree-traversal Practice Tags : StackTree Similar Reads Introduction to Tree Data Structure Tree data structure is a hierarchical structure that is used to represent and organize data in the form of parent child relationship. The following are some real world situations which are naturally a tree.Folder structure in an operating system.Tag structure in an HTML (root tag the as html tag) or 15+ min read Tree Traversal Techniques Tree Traversal techniques include various ways to visit all the nodes of the tree. Unlike linear data structures (Array, Linked List, Queues, Stacks, etc) which have only one logical way to traverse them, trees can be traversed in different ways. In this article, we will discuss all the tree travers 7 min read Applications of tree data structure A tree is a type of data structure that represents a hierarchical relationship between data elements, called nodes. The top node in the tree is called the root, and the elements below the root are called child nodes. Each child node may have one or more child nodes of its own, forming a branching st 4 min read Advantages and Disadvantages of Tree Tree is a non-linear data structure. It consists of nodes and edges. A tree represents data in a hierarchical organization. It is a special type of connected graph without any cycle or circuit.Advantages of Tree:Efficient searching: Trees are particularly efficient for searching and retrieving data. 2 min read Difference between an array and a tree Array:An array is a collection of homogeneous(same type) data items stored in contiguous memory locations. For example, if an array is of type âintâ, it can only store integer elements and cannot allow the elements of other types such as double, float, char, etc. The array is a linear data structure 3 min read Inorder Tree Traversal without Recursion Given a binary tree, the task is to perform in-order traversal of the tree without using recursion.Example:Input:Output: 4 2 5 1 3Explanation: Inorder traversal (Left->Root->Right) of the tree is 4 2 5 1 3Input:Output: 1 7 10 8 6 10 5 6Explanation: Inorder traversal (Left->Root->Right) o 8 min read Types of Trees in Data Structures A tree in data structures is a hierarchical data structure that consists of nodes connected by edges. It is used to represent relationships between elements, where each node holds data and is connected to other nodes in a parent-child relationship.Types of Trees TreeThe main types of trees in data s 4 min read Generic Trees (N-ary Tree)Introduction to Generic Trees (N-ary Trees)Generic trees are a collection of nodes where each node is a data structure that consists of records and a list of references to its children(duplicate references are not allowed). Unlike the linked list, each node stores the address of multiple nodes. Every node stores address of its children and t 5 min read Inorder traversal of an N-ary TreeGiven 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 finall 6 min read Preorder Traversal of an N-ary TreeGiven an N-ary Tree. The task is to write a program to perform the preorder traversal of the given n-ary tree. Examples: Input: 3-Array Tree 1 / | \ / | \ 2 3 4 / \ / | \ 5 6 7 8 9 / / | \ 10 11 12 13 Output: 1 2 5 10 6 11 12 13 3 4 7 8 9 Input: 3-Array Tree 1 / | \ / | \ 2 3 4 / \ / | \ 5 6 7 8 9 O 14 min read Iterative Postorder Traversal of N-ary TreeGiven an N-ary tree, the task is to find the post-order traversal of the given tree iteratively.Examples: Input: 1 / | \ 3 2 4 / \ 5 6 Output: [5, 6, 3, 2, 4, 1] Input: 1 / \ 2 3 Output: [2, 3, 1] Approach:We have already discussed iterative post-order traversal of binary tree using one stack. We wi 10 min read Level Order Traversal of N-ary TreeGiven an N-ary Tree. The task is to print the level order traversal of the tree where each level will be in a new line. Examples: Input: Image Output: 13 2 45 6Explanation: At level 1: only 1 is present.At level 2: 3, 2, 4 is presentAt level 3: 5, 6 is present Input: Image Output: 12 3 4 56 7 8 9 10 11 min read ZigZag Level Order Traversal of an N-ary TreeGiven a Generic Tree consisting of n nodes, the task is to find the ZigZag Level Order Traversal of the given tree.Note: A generic tree is a tree where each node can have zero or more children nodes. Unlike a binary tree, which has at most two children per node (left and right), a generic tree allow 8 min read Binary TreeIntroduction to Binary TreeBinary Tree is a non-linear and hierarchical data structure where each node has at most two children referred to as the left child and the right child. The topmost node in a binary tree is called the root, and the bottom-most nodes are called leaves. Introduction to Binary TreeRepresentation of Bina 15+ min read Properties of Binary TreeThis post explores the fundamental properties of a binary tree, covering its structure, characteristics, and key relationships between nodes, edges, height, and levelsBinary tree representationNote: Height of root node is considered as 0. Properties of Binary Trees1. Maximum Nodes at Level 'l'A bina 4 min read Applications, Advantages and Disadvantages of Binary TreeA binary tree is a tree that has at most two children for any of its nodes. There are several types of binary trees. To learn more about them please refer to the article on "Types of binary tree" Applications:General ApplicationsDOM in HTML: Binary trees help manage the hierarchical structure of web 2 min read Binary Tree (Array implementation)Given an array that represents a tree in such a way that array indexes are values in tree nodes and array values give the parent node of that particular index (or node). The value of the root node index would always be -1 as there is no parent for root. Construct the standard linked representation o 6 min read Complete Binary TreeWe know a tree is a non-linear data structure. It has no limitation on the number of children. A binary tree has a limitation as any node of the tree has at most two children: a left and a right child. What is a Complete Binary Tree?A complete binary tree is a special type of binary tree where all t 7 min read Perfect Binary TreeWhat is a Perfect Binary Tree? A perfect binary tree is a special type of binary tree in which all the leaf nodes are at the same depth, and all non-leaf nodes have two children. In simple terms, this means that all leaf nodes are at the maximum depth of the tree, and the tree is completely filled w 4 min read Ternary TreeCreate a Doubly Linked List from a Ternary TreeGiven a ternary tree, create a doubly linked list out of it. A ternary tree is just like a binary tree but instead of having two nodes, it has three nodes i.e. left, middle, and right. The doubly linked list should hold the following properties â The left pointer of the ternary tree should act as pr 12 min read Like