Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue)
Last Updated :
23 Jul, 2025
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 store inorder successor.
The following diagram shows an example Single Threaded Binary Tree. The dotted lines represent threads.

The following is a structure of a single-threaded binary tree.
C++
struct Node {
int key;
Node *left, *right;
// Used to indicate whether the right pointer is a normal right
// pointer or a pointer to inorder successor.
bool isThreaded;
};
Java
static class Node {
int key;
Node left, right;
// Used to indicate whether the right pointer is a normal right
// pointer or a pointer to inorder successor.
boolean isThreaded;
};
// This code is contributed by umadevi9616
Python3
class Node:
def __init__(self):
self.Key = 0;
self.left = None;
self.right = None;
# Used to indicate whether the right pointer is a normal right
# pointer or a pointer to inorder successor.
self.isThreaded = False;
# This code is contributed by Rajput-Ji
C#
class Node {
int key;
Node left, right;
// Used to indicate whether the right pointer is a normal right
// pointer or a pointer to inorder successor.
bool isThreaded;
};
// This code is contributed by Rajput-Ji
JavaScript
class Node
{
constructor(item)
{
// Used to indicate whether the right pointer is a normal
// right pointer or a pointer to inorder successor.
let isThreaded;
this.data=item;
this.left = this.right = null;
}
}
How to convert a Given Binary Tree to Threaded Binary Tree?
We basically need to set NULL right pointers to inorder successor. We first do an inorder traversal of the tree and store it in a queue (we can use a simple array also) so that the inorder successor becomes the next node. We again do an inorder traversal and whenever we find a node whose right is NULL, we take the front item from queue and make it the right of current node. We also set isThreaded to true to indicate that the right pointer is a threaded link.
Following is the implementation of the above idea.
C++
/* C++ program to convert a Binary Tree to Threaded Tree */
#include <bits/stdc++.h>
using namespace std;
/* Structure of a node in threaded binary tree */
struct Node {
int key;
Node *left, *right;
// Used to indicate whether the right pointer is a
// normal right pointer or a pointer to inorder
// successor.
bool isThreaded;
};
// Helper function to put the Nodes in inorder into queue
void populateQueue(Node* root, std::queue<Node*>* q)
{
if (root == NULL)
return;
if (root->left)
populateQueue(root->left, q);
q->push(root);
if (root->right)
populateQueue(root->right, q);
}
// Function to traverse queue, and make tree threaded
void createThreadedUtil(Node* root, std::queue<Node*>* q)
{
if (root == NULL)
return;
if (root->left)
createThreadedUtil(root->left, q);
q->pop();
if (root->right)
createThreadedUtil(root->right, q);
// If right pointer is NULL, link it to the
// inorder successor and set 'isThreaded' bit.
else {
root->right = q->front();
root->isThreaded = true;
}
}
// This function uses populateQueue() and
// createThreadedUtil() to convert a given binary tree
// to threaded tree.
void createThreaded(Node* root)
{
// Create a queue to store inorder traversal
std::queue<Node*> q;
// Store inorder traversal in queue
populateQueue(root, &q);
// Link NULL right pointers to inorder successor
createThreadedUtil(root, &q);
}
// A utility function to find leftmost node in a binary
// tree rooted with 'root'. This function is used in
// inOrder()
Node* leftMost(Node* root)
{
while (root != NULL && root->left != NULL)
root = root->left;
return root;
}
// Function to do inorder traversal of a threaded binary
// tree
void inOrder(Node* root)
{
if (root == NULL)
return;
// Find the leftmost node in Binary Tree
Node* cur = leftMost(root);
while (cur != NULL) {
cout << cur->key << " ";
// If this Node is a thread Node, then go to
// inorder successor
if (cur->isThreaded)
cur = cur->right;
else // Else go to the leftmost child in right
// subtree
cur = leftMost(cur->right);
}
}
// A utility function to create a new node
Node* newNode(int key)
{
Node* temp = new Node;
temp->left = temp->right = NULL;
temp->key = key;
return temp;
}
// Driver program to test above functions
int main()
{
/* 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);
createThreaded(root);
cout << "Inorder traversal of created threaded tree "
"is\n";
inOrder(root);
return 0;
}
Java
// Java program to convert binary tree to threaded tree
import java.util.LinkedList;
import java.util.Queue;
/* Class containing left and right child of current
node and key value*/
class Node {
int data;
Node left, right;
// Used to indicate whether the right pointer is a normal
// right pointer or a pointer to inorder successor.
boolean isThreaded;
public Node(int item)
{
data = item;
left = right = null;
}
}
class BinaryTree {
Node root;
// Helper function to put the Nodes in inorder into queue
void populateQueue(Node node, Queue<Node> q)
{
if (node == null)
return;
if (node.left != null)
populateQueue(node.left, q);
q.add(node);
if (node.right != null)
populateQueue(node.right, q);
}
// Function to traverse queue, and make tree threaded
void createThreadedUtil(Node node, Queue<Node> q)
{
if (node == null)
return;
if (node.left != null)
createThreadedUtil(node.left, q);
q.remove();
if (node.right != null)
createThreadedUtil(node.right, q);
// If right pointer is NULL, link it to the
// inorder successor and set 'isThreaded' bit.
else {
node.right = q.peek();
node.isThreaded = true;
}
}
// This function uses populateQueue() and
// createThreadedUtil() to convert a given binary tree
// to threaded tree.
void createThreaded(Node node)
{
// Create a queue to store inorder traversal
Queue<Node> q = new LinkedList<Node>();
// Store inorder traversal in queue
populateQueue(node, q);
// Link NULL right pointers to inorder successor
createThreadedUtil(node, q);
}
// A utility function to find leftmost node in a binary
// tree rooted with 'root'. This function is used in inOrder()
Node leftMost(Node node)
{
while (node != null && node.left != null)
node = node.left;
return node;
}
// Function to do inorder traversal of a threaded binary tree
void inOrder(Node node)
{
if (node == null)
return;
// Find the leftmost node in Binary Tree
Node cur = leftMost(node);
while (cur != null) {
System.out.print(" " + cur.data + " ");
// If this Node is a thread Node, then go to
// inorder successor
if (cur.isThreaded == true)
cur = cur.right;
else // Else go to the leftmost child in right subtree
cur = leftMost(cur.right);
}
}
// Driver program to test for above functions
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
tree.root.right.left = new Node(6);
tree.root.right.right = new Node(7);
tree.createThreaded(tree.root);
System.out.println("Inorder traversal of created threaded tree");
tree.inOrder(tree.root);
}
}
// This code has been contributed by Mayank Jaiswal
Python3
# Python3 program to convert
# a Binary Tree to Threaded Tree
# Structure of a node in threaded binary tree
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
# Used to indicate whether the right pointer
# is a normal right pointer or a pointer to
# inorder successor.
self.isThreaded = False
# Helper function to put the Nodes
# in inorder into queue
def populateQueue(root, q):
if root == None: return
if root.left:
populateQueue(root.left, q)
q.append(root)
if root.right:
populateQueue(root.right, q)
# Function to traverse queue,
# and make tree threaded
def createThreadedUtil(root, q):
if root == None: return
if root.left:
createThreadedUtil(root.left, q)
q.pop(0)
if root.right:
createThreadedUtil(root.right, q)
# If right pointer is None, link it to the
# inorder successor and set 'isThreaded' bit.
else:
if len(q) == 0: root.right = None
else: root.right = q[0]
root.isThreaded = True
# This function uses populateQueue() and
# createThreadedUtil() to convert a given
# binary tree to threaded tree.
def createThreaded(root):
# Create a queue to store inorder traversal
q = []
# Store inorder traversal in queue
populateQueue(root, q)
# Link None right pointers to inorder successor
createThreadedUtil(root, q)
# A utility function to find leftmost node
# in a binary tree rooted with 'root'.
# This function is used in inOrder()
def leftMost(root):
while root != None and root.left != None:
root = root.left
return root
# Function to do inorder traversal
# of a threaded binary tree
def inOrder(root):
if root == None: return
# Find the leftmost node in Binary Tree
cur = leftMost(root)
while cur != None:
print(cur.key, end = " ")
# If this Node is a thread Node,
# then go to inorder successor
if cur.isThreaded:
cur = cur.right
# Else go to the leftmost child
# in right subtree
else:
cur = leftMost(cur.right)
# Driver Code
if __name__ == "__main__":
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)
createThreaded(root)
print("Inorder traversal of created",
"threaded tree is")
inOrder(root)
# This code is contributed by Rituraj Jain
C#
// C# program to convert binary tree to threaded tree
using System;
using System.Collections.Generic;
/* Class containing left and right child of current
node and key value*/
public class Node {
public int data;
public Node left, right;
// Used to indicate whether the right pointer is a normal
// right pointer or a pointer to inorder successor.
public bool isThreaded;
public Node(int item)
{
data = item;
left = right = null;
}
}
public class BinaryTree {
Node root;
// Helper function to put the Nodes in inorder into queue
void populateQueue(Node node, Queue<Node> q)
{
if (node == null)
return;
if (node.left != null)
populateQueue(node.left, q);
q.Enqueue(node);
if (node.right != null)
populateQueue(node.right, q);
}
// Function to traverse queue, and make tree threaded
void createThreadedUtil(Node node, Queue<Node> q)
{
if (node == null)
return;
if (node.left != null)
createThreadedUtil(node.left, q);
q.Dequeue();
if (node.right != null)
createThreadedUtil(node.right, q);
// If right pointer is NULL, link it to the
// inorder successor and set 'isThreaded' bit.
else {
if (q.Count != 0)
node.right = q.Peek();
node.isThreaded = true;
}
}
// This function uses populateQueue() and
// createThreadedUtil() to convert a given binary tree
// to threaded tree.
void createThreaded(Node node)
{
// Create a queue to store inorder traversal
Queue<Node> q = new Queue<Node>();
// Store inorder traversal in queue
populateQueue(node, q);
// Link NULL right pointers to inorder successor
createThreadedUtil(node, q);
}
// A utility function to find leftmost node in a binary
// tree rooted with 'root'. This function is used in inOrder()
Node leftMost(Node node)
{
while (node != null && node.left != null)
node = node.left;
return node;
}
// Function to do inorder traversal of a threaded binary tree
void inOrder(Node node)
{
if (node == null)
return;
// Find the leftmost node in Binary Tree
Node cur = leftMost(node);
while (cur != null) {
Console.Write(" " + cur.data + " ");
// If this Node is a thread Node, then go to
// inorder successor
if (cur.isThreaded == true)
cur = cur.right;
else // Else go to the leftmost child in right subtree
cur = leftMost(cur.right);
}
}
// Driver code
public static void Main(String[] args)
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
tree.root.right.left = new Node(6);
tree.root.right.right = new Node(7);
tree.createThreaded(tree.root);
Console.WriteLine("Inorder traversal of created threaded tree");
tree.inOrder(tree.root);
}
}
// This code has been contributed by 29AjayKumar
JavaScript
<script>
// JavaScript program to convert
// binary tree to threaded tree
/* Class containing left and right child of current
node and key value*/
class Node
{
constructor(item)
{
// Used to indicate whether the right pointer is a normal
// right pointer or a pointer to inorder successor.
let isThreaded;
this.data=item;
this.left = this.right = null;
}
}
let root;
// Helper function to put the Nodes in inorder into queue
function populateQueue(node,q)
{
if (node == null)
return;
if (node.left != null)
populateQueue(node.left, q);
q.push(node);
if (node.right != null)
populateQueue(node.right, q);
}
// Function to traverse queue, and make tree threaded
function createThreadedUtil(node,q)
{
if (node == null)
return;
if (node.left != null)
createThreadedUtil(node.left, q);
q.shift();
if (node.right != null)
createThreadedUtil(node.right, q);
// If right pointer is NULL, link it to the
// inorder successor and set 'isThreaded' bit.
else {
node.right = q[0];
node.isThreaded = true;
}
}
// This function uses populateQueue() and
// createThreadedUtil() to convert a given binary tree
// to threaded tree.
function createThreaded(node)
{
// Create a queue to store inorder traversal
let q = [];
// Store inorder traversal in queue
populateQueue(node, q);
// Link NULL right pointers to inorder successor
createThreadedUtil(node, q);
}
// A utility function to find leftmost node in a binary
// tree rooted with 'root'. This function is used in inOrder()
function leftMost(node)
{
while (node != null && node.left != null)
node = node.left;
return node;
}
// Function to do inorder traversal of a threaded binary tree
function inOrder(node)
{
if (node == null)
return;
// Find the leftmost node in Binary Tree
let cur = leftMost(node);
while (cur != null) {
document.write(" " + cur.data + " ");
// If this Node is a thread Node, then go to
// inorder successor
if (cur.isThreaded == true)
cur = cur.right;
else // Else go to the leftmost child in right subtree
cur = leftMost(cur.right);
}
}
// Driver program to test for above functions
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);
createThreaded(root);
document.write(
"Inorder traversal of created threaded tree<br>"
);
inOrder(root);
// This code is contributed by rag2127
</script>
OutputInorder traversal of created threaded tree is
4 2 5 1 6 3 7
Time complexity: O(n)
Auxiliary space: O(n) // for queue q
Convert a Binary Tree to Threaded binary tree | Set 2 (Efficient)
Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data Structure GuideIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem