Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Tree
  • Practice Tree
  • MCQs on Tree
  • Tutorial on Tree
  • Types of Trees
  • Basic operations
  • Tree Traversal
  • Binary Tree
  • Complete Binary Tree
  • Ternary Tree
  • Binary Search Tree
  • Red-Black Tree
  • AVL Tree
  • Full Binary Tree
  • B-Tree
  • Advantages & Disadvantages
Open In App
Next Article:
Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue)
Next article icon

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

Last Updated : 15 Feb, 2023
Comments
Improve
Suggest changes
Like Article
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




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, data):
        self.key = data;
        self.left = none;
        self.right = none;
        self.isThreaded = false;
    # Used to indicate whether the right pointer is a normal right
    # pointer or a pointer to inorder successor.
 
# This code is contributed by umadevi9616
 
 

C#




public class Node {
    public int key;
    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;
};
 
 
// This code is contributed by umadevi9616
 
 

Javascript




/* structure of a node in threaded binary tree */
 class Node {
        constructor(val) {
            this.data = val;
            this.left = null;
            this.right = null;
     
   
    // Used to indicate whether the right pointer
    // is a normal right pointer or a pointer
    // to inorder successor.
    this.isThreaded = false;
    }
    }
     
    // This code is contributed by famously.
 
 

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++




/* 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;
};
 
// Converts tree with given root to threaded
// binary tree.
// This function returns rightmost child of
// root.
Node *createThreaded(Node *root)
{
    // Base cases : Tree is empty or has single
    //              node
    if (root == NULL)
        return NULL;
    if (root->left == NULL &&
        root->right == NULL)
        return root;
 
    // Find predecessor if it exists
    if (root->left != NULL)
    {
        // Find predecessor of root (Rightmost
        // child in left subtree)
        Node* l = createThreaded(root->left);
 
        // Link a thread from predecessor to
        // root.
        l->right = root;
        l->isThreaded = true;
    }
 
    // If current node is rightmost child
    if (root->right == NULL)
        return root;
 
    // Recur for right subtree.
    return createThreaded(root->right);
}
 
// 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 threadded
// 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 a Binary Tree to
    Threaded Tree */
import java.util.*;
class solution
{
  
   
/* structure of a node in threaded binary tree */
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;
};
   
// Converts tree with given root to threaded
// binary tree.
// This function returns rightmost child of
// root.
static Node createThreaded(Node root)
{
    // Base cases : Tree is empty or has single
    //              node
    if (root == null)
        return null;
    if (root.left == null &&
        root.right == null)
        return root;
   
    // Find predecessor if it exists
    if (root.left != null)
    {
        // Find predecessor of root (Rightmost
        // child in left subtree)
        Node l = createThreaded(root.left);
   
        // Link a thread from predecessor to
        // root.
        l.right = root;
        l.isThreaded = true;
    }
   
    // If current node is rightmost child
    if (root.right == null)
        return root;
   
    // Recur for right subtree.
    return createThreaded(root.right);
}
   
// A utility function to find leftmost node
// in a binary tree rooted with 'root'.
// This function is used in inOrder()
static Node leftMost(Node root)
{
    while (root != null && root.left != null)
        root = root.left;
    return root;
}
   
// Function to do inorder traversal of a threadded
// binary tree
static void inOrder(Node root)
{
    if (root == null) return;
   
    // Find the leftmost node in Binary Tree
    Node cur = leftMost(root);
   
    while (cur != null)
    {
        System.out.print(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
static Node newNode(int key)
{
    Node temp = new Node();
    temp.left = temp.right = null;
    temp.key = key;
    return temp;
}
   
// Driver program to test above functions
public static void main(String args[])
{
   /*       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);
   
    System.out.println("Inorder traversal of created "+"threaded tree is\n");
    inOrder(root); 
}
}
//contributed by Arnab Kundu
 
 

Python3




# Python3 program to convert a Binary Tree to
# Threaded Tree
 
# A utility function to create a new node
class newNode:
    def __init__(self, key):
        self.left = self.right = None
        self.key = key
        self.isThreaded = None
         
# Converts tree with given root to threaded
# binary tree.
# This function returns rightmost child of
# root.
def createThreaded(root):
     
    # Base cases : Tree is empty or has 
    #               single node
    if root == None:
        return None
    if root.left == None and root.right == None:
        return root
 
    # Find predecessor if it exists
    if root.left != None:
         
        # Find predecessor of root (Rightmost
        # child in left subtree)
        l = createThreaded(root.left)
 
        # Link a thread from predecessor
        # to root.
        l.right = root
        l.isThreaded = True
 
    # If current node is rightmost child
    if root.right == None:
        return root
 
    # Recur for right subtree.
    return createThreaded(root.right)
 
# 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: # Else go to the leftmost child
              # in right subtree
            cur = leftMost(cur.right)
 
# Driver Code
if __name__ == '__main__':
     
    #         1
    #     / \
    #     2 3
    #     / \ / \
    #     4 5 6 7
    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)
 
    print("Inorder traversal of created",
                      "threaded tree is")
    inOrder(root)
 
# This code is contributed by PranchalK
 
 

C#




using System;
 
/* C# program to convert a Binary Tree to 
    Threaded Tree */
public class solution
{
 
 
/* structure of a node in threaded binary tree */
public class Node
{
    public int key;
    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;
}
 
// Converts tree with given root to threaded 
// binary tree. 
// This function returns rightmost child of 
// root. 
public static Node createThreaded(Node root)
{
    // Base cases : Tree is empty or has single 
    //              node 
    if (root == null)
    {
        return null;
    }
    if (root.left == null && root.right == null)
    {
        return root;
    }
 
    // Find predecessor if it exists 
    if (root.left != null)
    {
        // Find predecessor of root (Rightmost 
        // child in left subtree) 
        Node l = createThreaded(root.left);
 
        // Link a thread from predecessor to 
        // root. 
        l.right = root;
        l.isThreaded = true;
    }
 
    // If current node is rightmost child 
    if (root.right == null)
    {
        return root;
    }
 
    // Recur for right subtree. 
    return createThreaded(root.right);
}
 
// A utility function to find leftmost node 
// in a binary tree rooted with 'root'. 
// This function is used in inOrder() 
public static Node leftMost(Node root)
{
    while (root != null && root.left != null)
    {
        root = root.left;
    }
    return root;
}
 
// Function to do inorder traversal of a threadded 
// binary tree 
public static void inOrder(Node root)
{
    if (root == null)
    {
        return;
    }
 
    // Find the leftmost node in Binary Tree 
    Node cur = leftMost(root);
 
    while (cur != null)
    {
        Console.Write(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 
public static Node newNode(int key)
{
    Node temp = new Node();
    temp.left = temp.right = null;
    temp.key = key;
    return temp;
}
 
// Driver program to test above functions 
public static void Main(string[] args)
{
   /*       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);
 
    Console.WriteLine("Inorder traversal of created " + "threaded tree is\n");
    inOrder(root);
}
}
 
  // This code is contributed by Shrikant13
 
 

Javascript




<script>
/* javascript program to convert a Binary Tree to
    Threaded Tree */
   
/* structure of a node in threaded binary tree */
 class Node {
        constructor(val) {
            this.data = val;
            this.left = null;
            this.right = null;
     
   
    // Used to indicate whether the right pointer
    // is a normal right pointer or a pointer
    // to inorder successor.
    this.isThreaded = false;
    }
    }
 
   
// Converts tree with given root to threaded
// binary tree.
// This function returns rightmost child of
// root.
function createThreaded(root)
{
    // Base cases : Tree is empty or has single
    //              node
    if (root == null)
        return null;
    if (root.left == null &&
        root.right == null)
        return root;
   
    // Find predecessor if it exists
    if (root.left != null)
    {
        // Find predecessor of root (Rightmost
        // child in left subtree)
        var l = createThreaded(root.left);
   
        // Link a thread from predecessor to
        // root.
        l.right = root;
        l.isThreaded = true;
    }
   
    // If current node is rightmost child
    if (root.right == null)
        return root;
   
    // Recur for right subtree.
    return createThreaded(root.right);
}
   
// A utility function to find leftmost node
// in a binary tree rooted with 'root'.
// This function is used in inOrder()
function leftMost(root)
{
    while (root != null && root.left != null)
        root = root.left;
    return root;
}
   
// Function to do inorder traversal of a threadded
// binary tree
function inOrder(root)
{
    if (root == null) return;
   
    // Find the leftmost node in Binary Tree
    var cur = leftMost(root);
   
    while (cur != null)
    {
        document.write(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
function newNode(key)
{
    var temp = new Node();
    temp.left = temp.right = null;
    temp.key = key;
    return temp;
}
   
// Driver program to test above functions
  
   /*       1
            / \
           2   3
          / \ / \
         4  5 6  7   */
    var 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);
   
    document.write("Inorder traversal of created "+"threaded tree is<br/>");
    inOrder(root); 
 
// This code contributed by aashish1995
</script>
 
 
Output
Inorder traversal of created threaded tree is 4 2 5 1 6 3 7 

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

 



Next Article
Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue)

G

Gopal Agarwal
Improve
Article Tags :
  • DSA
  • Tree
  • threaded-binary-tree
Practice Tags :
  • Tree

Similar Reads

  • Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue)
    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
    12 min read
  • Binary Tree to Binary Search Tree Conversion
    Given a Binary Tree, the task is to convert it to a Binary Search Tree. The conversion must be done in such a way that keeps the original structure of the Binary Tree. Examples Input: Output: Explanation: The above Binary tree is converted to Binary Search tree by keeping the original structure of B
    7 min read
  • Binary Tree to Binary Search Tree Conversion using STL set
    Given a Binary Tree, the task is to convert it to a Binary Search Tree. The conversion must be done in such a way that keeps the original structure of the Binary Tree. Example: Input: Output: Explanation: The above Binary tree is converted to Binary Search tree by keeping the original structure of B
    7 min read
  • Convert a given Binary tree to a tree that holds Logical AND property
    Given a Binary Tree (Every node has at most 2 children) where each node has value either 0 or 1. Convert a given Binary tree to a tree that holds Logical AND property, i.e., each node value should be the logical AND between its children. Examples: Input : The below tree doesn’t hold the logical AND
    7 min read
  • Convert an arbitrary Binary Tree to a tree that holds Children Sum Property - Set 2
    Given an arbitrary binary tree, your task is to convert it to a binary tree that holds the Children Sum Property, by incrementing the data values of any node. Note: The structure of tree can't be changed and the node values can't be decremented. Also, there exist multiple possible answers. Example:
    10 min read
  • Convert given binary tree to a XOR tree
    Given a Binary Tree where each node has a value of either 0 or 1, the task is to convert the given Binary tree to an XOR tree i.e a tree such that each node value is the logical XOR between its children. Note: Leaf nodes and nodes with one child are not considered as they don't have both children. E
    8 min read
  • Convert a given Binary tree to a tree that holds Logical OR property
    Given a Binary Tree (Every node has at most 2 children) where each node has value either 0 or 1. The task is to convert the given Binary tree to a tree that holds Logical OR property, i.e., each node value should be the logical OR between its children. Example: Input: 1 / \ 1 0 / \ / \ 0 1 1 1 Outpu
    7 min read
  • Check if a Binary Tree is subtree of another binary tree | Set 1
    Given two binary trees, check if the first tree is a subtree of the second one. A subtree of a tree T(root1) is a tree S(root2) consisting of a node in T and all of its descendants in T. The subtree corresponding to the root node is the entire tree and the subtree corresponding to any other node is
    9 min read
  • Check if a Binary tree is Subtree of another Binary tree | Set 3
    Given two binary trees, check if the first tree is a subtree of the second one. A subtree of a tree T(root1) is a tree S(root2) consisting of a node in T and all of its descendants in T. The subtree corresponding to the root node is the entire tree and the subtree corresponding to any other node is
    12 min read
  • Convert an arbitrary Binary Tree to a tree that holds Children Sum Property
    Given an arbitrary binary tree, your task is to convert it to a binary tree that holds Children Sum Property, by incrementing the data values of any node. Note: The structure of the tree can't be changed and the node values can't be decremented. Also, there exist multiple possible answers. Example:
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences