Inorder Non-threaded Binary Tree Traversal without Recursion or Stack
Last Updated :
17 Jul, 2022
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 root right". We can move to children using left and right pointers. Once a node is visited, we need to move to parent also. For example, in the above tree, we need to move to 10 after printing 5. For this purpose, we use parent pointer. Below is algorithm.
1. Initialize current node as root
2. Initialize a flag: leftdone = false;
3. Do following while root is not NULL
a) If leftdone is false, set current node as leftmost
child of node.
b) Mark leftdone as true and print current node.
c) If right child of current nodes exists, set current
as right child and set leftdone as false.
d) Else If parent exists, If current node is left child
of its parent, set current node as parent.
If current node is right child, keep moving to ancestors
using parent pointer while current node is right child
of its parent.
e) Else break (We have reached back to root)
Illustration:
Let us consider below tree for illustration.
10
/ \
5 100
/ \
80 120
Initialize: Current node = 10, leftdone = false
Since leftdone is false, we move to 5 (3.a), print it
and set leftdone = true.
Now we move to parent of 5 (3.d). Node 10 is
printed because leftdone is true.
We move to right of 10 and set leftdone as false (3.c)
Now current node is 100. Since leftdone is false, we move
to 80 (3.a) and set leftdone as true. We print current
node 80 and move back to parent 100 (3.d). Since leftdone
is true, we print current node 100.
Right of 100 exists, so we move to 120 (3.c). We print
current node 120.
Since 120 is right child of its parent we keep moving to parent
while parent is right child of its parent. We reach root. So
we break the loop and stop
Below is the implementation of above algorithm. Note that the implementation uses Binary Search Tree instead of Binary Tree. We can use the same function inorder() for Binary Tree also. The reason for using Binary Search Tree in below code is, it is easy to construct a Binary Search Tree with parent pointers and easy to test the outcome (In BST inorder traversal is always sorted).
C++
// C++ program to print inorder traversal of a Binary Search
// Tree (BST) without recursion and stack
#include <bits/stdc++.h>
using namespace std;
// BST Node
struct Node
{
Node *left, *right, *parent;
int key;
};
// A utility function to create a new BST node
Node *newNode(int item)
{
Node *temp = new Node;
temp->key = item;
temp->parent = temp->left = temp->right = NULL;
return temp;
}
/* A utility function to insert a new node with
given key in BST */
Node *insert(Node *node, int key)
{
/* If the tree is empty, return a new node */
if (node == NULL) return newNode(key);
/* Otherwise, recur down the tree */
if (key < node->key)
{
node->left = insert(node->left, key);
node->left->parent = node;
}
else if (key > node->key)
{
node->right = insert(node->right, key);
node->right->parent = node;
}
/* return the (unchanged) node pointer */
return node;
}
// Function to print inorder traversal using parent
// pointer
void inorder(Node *root)
{
bool leftdone = false;
// Start traversal from root
while (root)
{
// If left child is not traversed, find the
// leftmost child
if (!leftdone)
{
while (root->left)
root = root->left;
}
// Print root's data
printf("%d ", root->key);
// Mark left as done
leftdone = true;
// If right child exists
if (root->right)
{
leftdone = false;
root = root->right;
}
// If right child doesn't exist, move to parent
else if (root->parent)
{
// If this node is right child of its parent,
// visit parent's parent first
while (root->parent &&
root == root->parent->right)
root = root->parent;
if (!root->parent)
break;
root = root->parent;
}
else break;
}
}
int main(void)
{
Node * root = NULL;
root = insert(root, 24);
root = insert(root, 27);
root = insert(root, 29);
root = insert(root, 34);
root = insert(root, 14);
root = insert(root, 4);
root = insert(root, 10);
root = insert(root, 22);
root = insert(root, 13);
root = insert(root, 3);
root = insert(root, 2);
root = insert(root, 6);
printf("Inorder traversal is \n");
inorder(root);
return 0;
}
Java
/* Java program to print inorder traversal of a Binary Search Tree
without recursion and stack */
// BST node
class Node
{
int key;
Node left, right, parent;
public Node(int key)
{
this.key = key;
left = right = parent = null;
}
}
class BinaryTree
{
Node root;
/* A utility function to insert a new node with
given key in BST */
Node insert(Node node, int key)
{
/* If the tree is empty, return a new node */
if (node == null)
return new Node(key);
/* Otherwise, recur down the tree */
if (key < node.key)
{
node.left = insert(node.left, key);
node.left.parent = node;
}
else if (key > node.key)
{
node.right = insert(node.right, key);
node.right.parent = node;
}
/* return the (unchanged) node pointer */
return node;
}
// Function to print inorder traversal using parent
// pointer
void inorder(Node root)
{
boolean leftdone = false;
// Start traversal from root
while (root != null)
{
// If left child is not traversed, find the
// leftmost child
if (!leftdone)
{
while (root.left != null)
{
root = root.left;
}
}
// Print root's data
System.out.print(root.key + " ");
// Mark left as done
leftdone = true;
// If right child exists
if (root.right != null)
{
leftdone = false;
root = root.right;
}
// If right child doesn't exist, move to parent
else if (root.parent != null)
{
// If this node is right child of its parent,
// visit parent's parent first
while (root.parent != null
&& root == root.parent.right)
root = root.parent;
if (root.parent == null)
break;
root = root.parent;
}
else
break;
}
}
public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();
tree.root = tree.insert(tree.root, 24);
tree.root = tree.insert(tree.root, 27);
tree.root = tree.insert(tree.root, 29);
tree.root = tree.insert(tree.root, 34);
tree.root = tree.insert(tree.root, 14);
tree.root = tree.insert(tree.root, 4);
tree.root = tree.insert(tree.root, 10);
tree.root = tree.insert(tree.root, 22);
tree.root = tree.insert(tree.root, 13);
tree.root = tree.insert(tree.root, 3);
tree.root = tree.insert(tree.root, 2);
tree.root = tree.insert(tree.root, 6);
System.out.println("Inorder traversal is ");
tree.inorder(tree.root);
}
}
// This code has been contributed by Mayank Jaiswal(mayank_24)
Python3
# Python3 program to print inorder traversal of a
# Binary Search Tree (BST) without recursion and stack
# A utility function to create a new BST node
class newNode:
def __init__(self, item):
self.key = item
self.parent = self.left = self.right = None
# A utility function to insert a new
# node with given key in BST
def insert(node, key):
# If the tree is empty, return a new node
if node == None:
return newNode(key)
# Otherwise, recur down the tree
if key < node.key:
node.left = insert(node.left, key)
node.left.parent = node
elif key > node.key:
node.right = insert(node.right, key)
node.right.parent = node
# return the (unchanged) node pointer
return node
# Function to print inorder traversal
# using parent pointer
def inorder(root):
leftdone = False
# Start traversal from root
while root:
# If left child is not traversed,
# find the leftmost child
if leftdone == False:
while root.left:
root = root.left
# Print root's data
print(root.key, end = " ")
# Mark left as done
leftdone = True
# If right child exists
if root.right:
leftdone = False
root = root.right
# If right child doesn't exist, move to parent
elif root.parent:
# If this node is right child of its
# parent, visit parent's parent first
while root.parent and root == root.parent.right:
root = root.parent
if root.parent == None:
break
root = root.parent
else:
break
# Driver Code
if __name__ == '__main__':
root = None
root = insert(root, 24)
root = insert(root, 27)
root = insert(root, 29)
root = insert(root, 34)
root = insert(root, 14)
root = insert(root, 4)
root = insert(root, 10)
root = insert(root, 22)
root = insert(root, 13)
root = insert(root, 3)
root = insert(root, 2)
root = insert(root, 6)
print("Inorder traversal is ")
inorder(root)
# This code is contributed by PranchalK
C#
// C# program to print inorder traversal
// of a Binary Search Tree without
// recursion and stack
using System;
// BST node
class Node
{
public int key;
public Node left, right, parent;
public Node(int key)
{
this.key = key;
left = right = parent = null;
}
}
class BinaryTree
{
Node root;
/* A utility function to insert a
new node with given key in BST */
Node insert(Node node, int key)
{
/* If the tree is empty,
return a new node */
if (node == null)
return new Node(key);
/* Otherwise, recur down the tree */
if (key < node.key)
{
node.left = insert(node.left, key);
node.left.parent = node;
}
else if (key > node.key)
{
node.right = insert(node.right, key);
node.right.parent = node;
}
/* return the (unchanged) node pointer */
return node;
}
// Function to print inorder traversal
// using parent pointer
void inorder(Node root)
{
Boolean leftdone = false;
// Start traversal from root
while (root != null)
{
// If left child is not traversed,
// find the leftmost child
if (!leftdone)
{
while (root.left != null)
{
root = root.left;
}
}
// Print root's data
Console.Write(root.key + " ");
// Mark left as done
leftdone = true;
// If right child exists
if (root.right != null)
{
leftdone = false;
root = root.right;
}
// If right child doesn't exist,
// move to parent
else if (root.parent != null)
{
// If this node is right child
// of its parent, visit parent's
// parent first
while (root.parent != null &&
root == root.parent.right)
root = root.parent;
if (root.parent == null)
break;
root = root.parent;
}
else
break;
}
}
// Driver Code
static public void Main(String[] args)
{
BinaryTree tree = new BinaryTree();
tree.root = tree.insert(tree.root, 24);
tree.root = tree.insert(tree.root, 27);
tree.root = tree.insert(tree.root, 29);
tree.root = tree.insert(tree.root, 34);
tree.root = tree.insert(tree.root, 14);
tree.root = tree.insert(tree.root, 4);
tree.root = tree.insert(tree.root, 10);
tree.root = tree.insert(tree.root, 22);
tree.root = tree.insert(tree.root, 13);
tree.root = tree.insert(tree.root, 3);
tree.root = tree.insert(tree.root, 2);
tree.root = tree.insert(tree.root, 6);
Console.WriteLine("Inorder traversal is ");
tree.inorder(tree.root);
}
}
// This code is contributed by Arnab Kundu
JavaScript
<script>
/* javascript program to print inorder traversal of a Binary Search Tree
without recursion and stack */
// BST node
class Node {
constructor(key) {
this.key = key;
this.left = this.right = this.parent = null;
}
}
var root = null;
/*
* A utility function to insert a new node with given key in BST
*/
function insert(node , key) {
/* If the tree is empty, return a new node */
if (node == null)
return new Node(key);
/* Otherwise, recur down the tree */
if (key < node.key) {
node.left = insert(node.left, key);
node.left.parent = node;
} else if (key > node.key) {
node.right = insert(node.right, key);
node.right.parent = node;
}
/* return the (unchanged) node pointer */
return node;
}
// Function to print inorder traversal using parent
// pointer
function inorder(root) {
var leftdone = false;
// Start traversal from root
while (root != null) {
// If left child is not traversed, find the
// leftmost child
if (!leftdone) {
while (root.left != null) {
root = root.left;
}
}
// Print root's data
document.write(root.key + " ");
// Mark left as done
leftdone = true;
// If right child exists
if (root.right != null) {
leftdone = false;
root = root.right;
}
// If right child doesn't exist, move to parent
else if (root.parent != null) {
// If this node is right child of its parent,
// visit parent's parent first
while (root.parent != null && root == root.parent.right)
root = root.parent;
if (root.parent == null)
break;
root = root.parent;
} else
break;
}
}
root = insert(root, 24);
root = insert(root, 27);
root = insert(root, 29);
root = insert(root, 34);
root = insert(root, 14);
root = insert(root, 4);
root = insert(root, 10);
root = insert(root, 22);
root = insert(root, 13);
root = insert(root, 3);
root = insert(root, 2);
root = insert(root, 6);
document.write("Inorder traversal is ");
inorder(root);
// This code contributed by aashish1995
</script>
Output:
Inorder traversal is
2 3 4 6 10 13 14 22 24 27 29 34
Time complexity: O(n) where n is no of nodes
Auxiliary Space: O(n)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read