The Wayback Machine - https://web.archive.org/web/20240909115138/https://www.geeksforgeeks.org/threaded-binary-tree/
Open In App

Threaded Binary Tree

Last Updated : 26 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Solve Problem
Medium
64.78%
78.9K

Inorder traversal of a Binary tree can either be done using recursion or with the use of a auxiliary stack. The idea of threaded binary trees is to make inorder traversal faster and do it without stack and without recursion. A binary tree is made threaded by making all right child pointers that would normally be NULL point to the inorder successor of the node (if it exists).

A threaded binary tree is a type of binary tree data structure where the empty left and right child pointers in a binary tree are replaced with threads that link nodes directly to their in-order predecessor or successor, thereby providing a way to traverse the tree without using recursion or a stack.

Threaded binary trees can be useful when space is a concern, as they can eliminate the need for a stack during traversal. However, they can be more complex to implement than standard binary trees.


There are two types of threaded binary trees. 
Single Threaded: Where a NULL right pointers is made to point to the inorder successor (if successor exists)
Double Threaded: Where both left and right NULL pointers are made to point to inorder predecessor and inorder successor respectively. The predecessor threads are useful for reverse inorder traversal and postorder traversal.
The threads are also useful for fast accessing ancestors of a node.
Following diagram shows an example Single Threaded Binary Tree. The dotted lines represent threads. 

threadedBT


C and C++ representation of a Threaded Node 
Following is C and C++representation of a single-threaded node.

C++
// Use any below method to represent a Threaded Node

// Method 1: Using "struct" to make
// user-define data type
struct node {
    int data;
    struct node* left;
    struct node* right;
    bool rightThread;
};

// Method 2: Using "class" to make
// user-define data type
class Node {
public:
    int data;
    Node* left;
    Node* right;
    bool rightThread;
    // Val is the key or the value that has to be added to
    // the data part
    Node(int val){
        data = val;
        // Left and right child for node will be initialized
        // to null
        left = NULL;
        right = NULL;
        // rightThread will be initialized to false
        rightThread = false;
    }
};

// This code is contributed by Susobhan Akhuli
C
typedef struct Node {
    int data;
    struct Node* left;
    struct Node* right;
    bool rightThread;
} Node;

// Constructor function
Node* createNode(int val) {
    Node* newNode = (Node*)malloc(sizeof(Node));
    if (newNode != NULL) {
        newNode->data = val;
        newNode->left = NULL;
        newNode->right = NULL;
        newNode->rightThread = false;
    }
    return newNode;
}
JavaScript
// Method 1: Using "struct" to define a threaded node
class ThreadedNode1 {
    constructor(data) {
        this.data = data;
        this.left = null;
        this.right = null;
        this.rightThread = false;
    }
}

// Method 2: Using "class" to define a threaded node
class ThreadedNode2 {
    constructor(data) {
        this.data = data;
        this.left = null;
        this.right = null;
        this.rightThread = false;
    }
}

Java representation of a Threaded Node

Following is Java representation of a single-threaded node.

Java
static class Node 
{
    int data;
    Node left, right;
    boolean rightThread;  
}

// This code contributed by aashish1995 

Python3 representation of a Threaded Node

Following is Python3 representation of a single-threaded node.

Python3
class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
        self.rightThread = False

Since right pointer is used for two purposes, the boolean variable rightThread is used to indicate whether right pointer points to right child or inorder successor. Similarly, we can add leftThread for a double threaded binary tree.
Inorder Traversal using Threads 
Following is code for inorder traversal in a threaded binary tree.

C++
// Utility function to find leftmost node in a tree rooted with n
Node* leftMost(Node* n){
    if (n == NULL)
        return NULL;

    while (n->left != NULL)
        n = n->left;

    return n;
}

// CPP code to do inorder traversal in a threaded binary tree
void inOrder(Node* root){
    Node* cur = leftMost(root);
    while (cur != NULL) {
        cout<<cur->data<<" ";

        // If this node is a thread node, then go to
        // inorder successor
        if (cur->rightThread)
            cur = cur->right;
        else // Else go to the leftmost child in right
             // subtree
            cur = leftmost(cur->right);
    }
}

// This code is contributed by Susobhan Akhuli
C
// Utility function to find leftmost node in a tree rooted
// with n
struct Node* leftMost(struct Node* n)
{
    if (n == NULL)
        return NULL;

    while (n->left != NULL)
        n = n->left;

    return n;
}

// C code to do inorder traversal in a threaded binary tree
void inOrder(struct Node* root)
{
    struct Node* cur = leftMost(root);
    while (cur != NULL) {
        printf("%d ", cur->data);

        // If this node is a thread node, then go to
        // inorder successor
        if (cur->rightThread)
            cur = cur->right;
        else // Else go to the leftmost child in right
             // subtree
            cur = leftmost(cur->right);
    }
}
Java
// Utility function to find leftmost node in a tree rooted
// with n
Node leftMost(Node n)
{
    if (n == null)
        return null;

    while (n.left != null)
        n = n.left;

    return n;
}

// C code to do inorder traversal in a threaded binary tree
static void inOrder(Node root)
{
    Node cur = leftMost(root);
    while (cur != null) {
        System.out.printf("%d ", cur.data);

        // If this node is a thread node, then go to
        // inorder successor
        if (cur.rightThread)
            cur = cur.right;
        else // Else go to the leftmost child in right
             // subtree
            cur = leftmost(cur.right);
    }
}

// This code contributed by aashish1995
C#
// Utility function to find leftmost node in a tree rooted
// with n
Node leftMost(Node n)
{
  if (n == null)
    return null;

  while (n.left != null)
    n = n.left;

  return n;
}

// C code to do inorder traversal in a threaded binary tree
static void inOrder(Node root)
{
  Node cur = leftMost(root);
  while (cur != null) 
  {
    Console.Write("{0} ", cur.data);

    // If this node is a thread node, then go to
    // inorder successor
    if (cur.rightThread)
      cur = cur.right;
    else // Else go to the leftmost child in right
      // subtree
      cur = leftmost(cur.right);
  }
}

// This code is contributed by gauravrajput1
JavaScript
<script>

// Utility function to find leftmost node in a tree rooted
// with n
function leftMost(n)
{
    if (n == null)
        return null;
 
    while (n.left != null)
        n = n.left;
 
    return n;
}

// JavaScript code to do inorder traversal in 
// a threaded binary tree
function inOrder(root)
{
    let cur = leftMost(root);
    while (cur != null) {
        document.write(cur.data+" ");
 
        // If this node is a thread node, then go to
        // inorder successor
        if (cur.rightThread)
            cur = cur.right;
        else // Else go to the leftmost child in right
             // subtree
            cur = leftmost(cur.right);
        }
}

// This code is contributed by unknown2108

</script>
Python3
# Utility function to find leftmost Node in a tree rooted
# with n
def leftMost(n):

    if (n == None):
        return None;

    while (n.left != None):
        n = n.left;

    return n;


# C code to do inorder traversal in a threaded binary tree
def inOrder(root):

    cur = leftMost(root);
    while (cur != None):
        print(cur.data," ");

        # If this Node is a thread Node, then go to
        # inorder successor
        if (cur.rightThread):
            cur = cur.right;
        else: # Else go to the leftmost child in right
             # subtree
            cur = leftmost(cur.right);

# This code is contributed by Rajput-Ji 

Following diagram demonstrates inorder order traversal using threads.
 

threadedTraversal

Advantages of Threaded Binary Tree

  • In this Tree it enables linear traversal of elements.
  • It eliminates the use of stack as it perform linear traversal, so save memory.
  • Enables to find parent node without explicit use of parent pointer
  • Threaded tree give forward and backward traversal of nodes by in-order fashion
  • Nodes contain pointers to in-order predecessor and successor
  • For a given node, we can easily find inorder predecessor and successor. So, searching is much more easier.
  •  In threaded binary tree there is no NULL pointer present. Hence memory wastage in occupying NULL links is avoided.
  • The threads are pointing to successor and predecessor nodes. This makes us to obtain predecessor and successor node of any node quickly. 
  • There is no need of stack while traversing the tree, because using thread links we can reach to previously visited nodes.

Disadvantages of Threaded Binary Tree

  • Every node in threaded binary tree need extra information(extra memory) to indicate whether its left or right node indicated its child nodes or its inorder predecessor or successor. So, the node consumes extra memory to implement.
  • Insertion and deletion are way more complex and time consuming than the normal one since both threads and ordinary links need to be maintained.
  • Implementing threads for every possible node is complicated.
  • Increased complexity: Implementing a threaded binary tree requires more complex algorithms and data structures than a regular binary tree. This can make the code harder to read and debug.
  • Extra memory usage: In some cases, the additional pointers used to thread the tree can use up more memory than a regular binary tree. This is especially true if the tree is not fully balanced, as threading a skewed tree can result in a large number of additional pointers.
  • Limited flexibility: Threaded binary trees are specialized data structures that are optimized for specific types of traversal. While they can be more efficient than regular binary trees for these types of operations, they may not be as useful in other scenarios. For example, they cannot be easily modified (e.g. inserting or deleting nodes) without breaking the threading.
  • Difficulty in parallelizing: It can be challenging to parallelize operations on a threaded binary tree, as the threading can introduce data dependencies that make it difficult to process nodes independently. This can limit the performance gains that can be achieved through parallelism.

Applications of threaded binary tree –

  • Expression evaluation: Threaded binary trees can be used to evaluate arithmetic expressions in a way that avoids recursion or a stack. The tree can be constructed from the input expression, and then traversed in-order or pre-order to perform the evaluation.
  • Database indexing: In a database, threaded binary trees can be used to index data based on a specific field (e.g. last name). The tree can be constructed with the indexed values as keys, and then traversed in-order to retrieve the data in sorted order.
  • Symbol table management: In a compiler or interpreter, threaded binary trees can be used to store and manage symbol tables for variables and functions. The tree can be constructed with the symbols as keys, and then traversed in-order or pre-order to perform various operations on the symbol table.
  • Disk-based data structures: Threaded binary trees can be used in disk-based data structures (e.g. B-trees) to improve performance. By threading the tree, it can be traversed in a way that minimizes disk seeks and improves locality of reference.
  • Navigation of hierarchical data: In certain applications, threaded binary trees can be used to navigate hierarchical data structures, such as file systems or web site directories. The tree can be constructed from the hierarchical data, and then traversed in-order or pre-order to efficiently access the data in a specific order.

We will soon be discussing insertion and deletion in threaded binary trees.
Sources: 
http://en.wikipedia.org/wiki/Threaded_binary_tree 
www.cs.berkeley.edu/~kamil/teaching/su02/080802.ppt



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 store inorder successor. The following diagram sho
12 min read
Convert a Binary Tree to Threaded binary tree | Set 2 (Efficient)
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 do
12 min read
Reverse Morris traversal using Threaded Binary Tree
What is Morris traversal?Morris (InOrder) Traversal is a tree traversal algorithm that does not use recursion or stacks. This traversal creates links as descendants and outputs nodes using those links. Finally, undo the changes to restore the original tree.Given a binary tree, task is to do reverse inorder traversal using Morris Traversal. Prerequi
10 min read
Double Threaded Binary Search Tree
Double Threaded Binary Search Tree: is a binary search tree in which the nodes are not every left NULL pointer points to its inorder predecessor and the right NULL pointer points to the inorder successor.The threads are also useful for fast accessing the ancestors of a node.  Double Threaded Binary Search Tree is one of the most used types of Advan
15+ min read
Inorder Non-threaded Binary Tree Traversal without Recursion or Stack
We have discussed Thread based Morris Traversal. Can we do inorder traversal without threads if we have parent pointers available to us? Input: Root of Below Tree [Every node of tree has parent pointer also] 10 / \ 5 100 / \ 80 120 Output: 5 10 80 100 120 The code should not extra space (No Recursion and stack) In inorder traversal, we follow "left
11 min read
Threaded Binary Tree | Insertion
We have already discuss the Binary Threaded Binary Tree.Insertion in Binary threaded tree is similar to insertion in binary tree but we will have to adjust the threads after insertion of each element. C representation of Binary Threaded Node: struct Node { struct Node *left, *right; int info; // false if left pointer points to predecessor // in Ino
13 min read
Threaded Binary Search Tree | Deletion
A threaded binary tree node looks like following. C/C++ Code struct Node { struct Node *left, *right; int info; // false if left pointer points to predecessor // in Inorder Traversal bool lthread; // false if right pointer points to predecessor // in Inorder Traversal bool rthread; }; Java Code static class Node { Node left, right; int info; // Tru
15+ min read
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
In this article, we will discuss the complexity of different operations in binary trees including BST and AVL trees. Before understanding this article, you should have a basic idea about Binary Tree, Binary Search Tree, and AVL Tree. The main operations in a binary tree are: search, insert and delete. We will see the worst-case time complexity of t
4 min read
Convert a Generic Tree(N-array Tree) to Binary Tree
Prerequisite: Generic Trees(N-array Trees) In this article, we will discuss the conversion of the Generic Tree to a Binary Tree. Following are the rules to convert a Generic(N-array Tree) to a Binary Tree: The root of the Binary Tree is the Root of the Generic Tree.The left child of a node in the Generic Tree is the Left child of that node in the B
13 min read
Check whether a binary tree is a full binary tree or not | Iterative Approach
Given a binary tree containing n nodes. The problem is to check whether the given binary tree is a full binary tree or not. A full binary tree is defined as a binary tree in which all nodes have either zero or two child nodes. Conversely, there is no node in a full binary tree, which has only one child node. Examples: Input : 1 / \ 2 3 / \ 4 5 Outp
8 min read
Binary Tree to Binary Search Tree Conversion using STL set
Given a Binary Tree, 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.This solution will use Sets of C++ STL instead of array-based solution. Examples: Example 1 Input: 10 / \ 2 7 / \ 8 4 Output: 8 / \ 4 10 / \ 2 7 Example 2 Input: 10 / \ 30 15 / \ 20 5 Output: 15 / \
12 min read
Check whether a given binary tree is skewed binary tree or not?
Given a Binary Tree check whether it is skewed binary tree or not. A skewed tree is a tree where each node has only one child node or none. Examples: Input : 5 / 4 \ 3 / 2 Output : Yes Input : 5 / 4 \ 3 / \ 2 4 Output : No The idea is to check if a node has two children. If node has two children return false, else recursively compute whether subtre
13 min read
Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
Given two binary trees S and T, the task is the check that if S is a subtree of the Tree T. For Example: Input: Tree T - 1 / \ 2 3 / \ / \ 4 5 6 7 Tree S - 2 / \ 4 5 Output: YES Explanation: The above tree is the subtree of the tree T, Hence the output is YES Approach: The idea is to traverse both the tree in Pre-order Traversal and check for each
11 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 is a tree S consisting of a node in T and all of its descendants in T. The subtree corresponding to the root node is the entire tree; the subtree corresponding to any other node is called a proper subtree. Examples: Input: Tree-T Tree-S 1 3 / \ / 2
15 min read
Check whether a binary tree is a full binary tree or not
A full binary tree is defined as a binary tree in which all nodes have either zero or two child nodes. Conversely, there is no node in a full binary tree, which has one child node. More information about full binary trees can be found here. For Example : Recommended PracticeFull binary treeTry It! To check whether a binary tree is a full binary tre
14 min read
Check if a binary tree is subtree of another binary tree | Set 2
Given two binary trees, check if the first tree is a subtree of the second one. A subtree of a tree T is a tree S consisting of a node in T and all of its descendants in T. The subtree corresponding to the root node is the entire tree; the subtree corresponding to any other node is called a proper subtree.For example, in the following case, Tree1 i
15+ min read
Minimum swap required to convert binary tree to binary search tree
Given the array representation of Complete Binary Tree i.e, if index i is the parent, index 2*i + 1 is the left child and index 2*i + 2 is the right child. The task is to find the minimum number of swap required to convert it into Binary Search Tree. Examples: Input : arr[] = { 5, 6, 7, 8, 9, 10, 11 } Output : 3 Binary tree of the given array: Swap
8 min read
Difference between Binary Tree and Binary Search Tree
Binary Tree Data Structure:A tree whose elements have at most 2 children is called a binary tree. Since each element in a binary tree can have only 2 children, we typically name them the left and right children.  Binary Search Tree Data Structure (BST):A binary search tree is a hierarchical data structure where each node has at most two children, w
2 min read
Binary Tree to Binary Search Tree Conversion
Given a Binary Tree, convert it to a Binary Search Tree. The conversion must be done in such a way that keeps the original structure of Binary Tree. Examples Example 1Input: 10 / \ 2 7 / \ 8 4Output: 8 / \ 4 10 / \ 2 7Example 2Input: 10 / \ 30 15 / \ 20 5Output: 15 / \ 10 20 / \ 5 30Solution: Following is a 3 step solution for converting Binary tre
15+ 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 is a tree S consisting of a node in T and all of its descendants in T. The subtree corresponding to the root node is the entire tree; the subtree corresponding to any other node is called a proper subtree. Examples: Input: Tree S 10 / \ 4 6 \ 30 Tr
11 min read
Check if a given Binary Tree is height balanced like a Red-Black Tree
In a Red-Black Tree, the maximum height of a node is at most twice the minimum height (The four Red-Black tree properties make sure this is always followed). Given a Binary Search Tree, we need to check for following property. For every node, length of the longest leaf to node path has not more than twice the nodes on shortest path from node to lea
9 min read
Check whether a binary tree is a complete tree or not | Set 2 (Recursive Solution)
A complete binary tree is a binary tree whose all levels except the last level are completely filled and all the leaves in the last level are all to the left side. More information about complete binary trees can be found here. Example:Below tree is a Complete Binary Tree (All nodes till the second last nodes are filled and all leaves are to the le
10 min read
Print Binary Tree levels in sorted order | Set 3 (Tree given as array)
Given a Complete Binary Tree as an array, the task is to print all of its levels in sorted order.Examples: Input: arr[] = {7, 6, 5, 4, 3, 2, 1} The given tree looks like 7 / \ 6 5 / \ / \ 4 3 2 1 Output: 7 5 6 1 2 3 4 Input: arr[] = {5, 6, 4, 9, 2, 1} The given tree looks like 5 / \ 6 4 / \ / 9 2 1 Output: 5 4 6 1 2 9 Approach: A similar problem is
6 min read
Check if the given binary tree has a sub-tree with equal no of 1's and 0's | Set 2
Given a tree having every node's value as either 0 or 1, the task is to find whether the given binary tree contains any sub-tree that has equal number of 0's and 1's, if such sub-tree is found then print Yes else print No.Examples: Input: Output: Yes There are two sub-trees with equal number of 1's and 0's. Hence the output is "Yes"Input: Output: N
10 min read
Check if the given n-ary tree is a binary tree
Given an n-ary tree, the task is to check whether the given tree is binary or not. Examples: Input: A / \ B C / \ \ D E F Output: Yes Input: A / | \ B C D \ F Output: No Approach: Every node in a binary tree can have at most 2 children. So, for every node of the given tree, count the number of children and if for any node the count exceeds 2 then p
6 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 Output: 0 1 1 1 1 1 1Explanation: Given Tree 1 / \ 1 0
7 min read
Difference between General tree and Binary tree
General Tree: In the data structure, General tree is a tree in which each node can have either zero or many child nodes. It can not be empty. In general tree, there is no limitation on the degree of a node. The topmost node of a general tree is called the root node. There are many subtrees in a general tree. The subtree of a general tree is unorder
2 min read
Construct XOR tree by Given leaf nodes of Perfect Binary Tree
Given the leaf nodes of a perfect binary tree, the task is to construct the XOR tree and print the root node of this tree. An XOR tree is a tree whose parent node is the XOR of the left child and the right child node of the tree. Parent node = Left child node ^ Right child node Examples: Input: arr = {40, 32, 12, 1, 4, 3, 2, 7} Output: Nodes of the
12 min read
Min-Max Product Tree of a given Binary Tree
Given a Binary Tree, the task is to convert the given Binary tree into Min-Max Product Tree and print the level-order sequence of the modified tree. Min-Max Product Tree: A Min-Max Product Tree contains the product of the minimum and maximum values of its left and right subtrees at each node. Note: For any node having only a single child, the value
14 min read
Convert a Binary Search Tree into a Skewed tree in increasing or decreasing order
Given a Binary Search Tree and a binary integer K, the task is to convert Binary search tree into a Skewed Tree in increasing order if K = 0 or in decreasing order if K = 1. Examples: Input: K = 0, 5 / \ 3 6 Output: 3 \ 5 \ 6 Input: K = 1, 2 / \ 1 3 Output: 3 \ 2 \ 1 Approach: The key observation in the problem is that the first node of the skewed
10 min read
Article Tags :
Practice Tags :