Open In App

Convert a Binary Tree to Threaded binary tree | Set 2 (Efficient)

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
13 Likes
Like
Report

Idea of Threaded Binary Tree 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.

Following diagram shows an example Single Threaded Binary Tree. The dotted lines represent threads. 

threadedBT

Following is 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 Python3 C# JavaScript

How to convert a Given Binary Tree to Threaded Binary Tree? 

We have discussed a Queue-based solution here. In this post, space-efficient solution is discussed that doesn't require a queue.
The idea is based on the fact that we link from inorder predecessor to a node. We link those inorder predecessor which lie in subtree of node. So we find inorder predecessor of a node if its left is not NULL. Inorder predecessor of a node (whose left is NULL) is a rightmost node in the left child. Once we find the predecessor, we link a thread from it to the current node. 

Following is the implementation of the above idea. 

C++
Java Python3 C# JavaScript

Output
Inorder traversal of created threaded tree is
4 2 5 1 6 3 7 

Time complexity: O(n).
space complexity: O(1).

 


Convert a Binary Tree to Threaded binary tree | Set 2 (Efficient)
Article Tags :
Practice Tags :

Similar Reads