Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue) - GeeksforGeeks

28 Jan, 2022
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. Where-ever 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.  
Following is structure of a single-threaded binary tree.  
C
Java
Python3
C#
Javascript
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;};
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
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
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
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++
Java
Python3
C#
Javascript
/* 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 queuevoid 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 threadedvoid 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 treevoid 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 nodeNode* newNode(int key){    Node* temp = new Node;    temp->left = temp->right = NULL;    temp->key = key;    return temp;} // Driver program to test above functionsint 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 program to convert binary tree to threaded treeimport 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 program to convert# a Binary Tree to Threaded Tree # Structure of a node in threaded binary treeclass 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 queuedef 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 threadeddef 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 treedef 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 Codeif __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# program to convert binary tree to threaded treeusing System;using System.Collections.Generic; /* Class containing left and right child of currentnode 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
<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 queuefunction 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 threadedfunction 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 treefunction 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 functionsroot = 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>
Output:  
Inorder traversal of created threaded tree is
4 2 5 1 6 3 7
 
YouTubeGeeksforGeeks507K subscribersConvert a Binary Tree to Threaded binary tree | Set 1 (Using Queue) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 6:31•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=Qjietvp72_Q" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Convert a Binary Tree to Threaded binary tree | Set 2 (Efficient)This article is contributed by Minhaz. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above 
rituraj_jain
29AjayKumar
rag2127
rutvik_56
umadevi9616
Rajput-Ji
threaded-binary-tree
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Binary Tree | Set 3 (Types of Binary Tree)
Inorder Tree Traversal without Recursion
Binary Tree | Set 2 (Properties)
Decision Tree
A program to check if a binary tree is BST or not
Construct Tree from given Inorder and Preorder traversals
Introduction to Tree Data Structure
Lowest Common Ancestor in a Binary Tree | Set 1
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree