# Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue) in C++

C++Server Side ProgrammingProgramming

In this tutorial, we will be discussing a program to convert a binary tree to a threaded binary tree using a queue data structure.

For this, we will be provided with a binary tree. Our task is to convert that particular binary tree into a threaded binary tree by adding additional routes for quicker inorder traversal with the help of a queue data structure.

## Example

Live Demo

#include <iostream>
#include <queue>
using namespace std;
struct Node {
int key;
Node *left, *right;
};
//putting the inorder pattern into a queue
void convert_queue(Node* root, std::queue<Node*>* q){
if (root == NULL)
return;
if (root->left)
convert_queue(root->left, q);
q->push(root);
if (root->right)
convert_queue(root->right, q);
}
//traversing the queue and making threaded tree
if (root == NULL)
return;
if (root->left)
q->pop();
if (root->right)
//if right pointer in NUll, point it to
//inorder successor
else {
root->right = q->front();
}
}
//finally taking the tree and converting it into threaded
std::queue<Node*> q;
convert_queue(root, &q);
}
Node* leftMost(Node* root){
while (root != NULL && root->left != NULL)
root = root->left;
return root;
}
//performing inorder traversal of threaded tree
void inOrder(Node* root){
if (root == NULL)
return;
Node* cur = leftMost(root);
while (cur != NULL) {
cout << cur->key << " ";
//if threaded node, move to inorder successor
cur = cur->right;
else
cur = leftMost(cur->right);
}
}
Node* newNode(int key){
Node* temp = new Node;
temp->left = temp->right = NULL;
temp->key = key;
return temp;
}
int main(){
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);
}
Traversing threaded tree :
4 2 5 1 6 3 7