Threaded Binary Tree

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.

                                         JavaScript

Java representation of a Threaded Node

Following is Java representation of a single-threaded node.

Python3 representation of a Threaded Node

Following is Python3 representation of a single-threaded node.

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.

                                                  Java
JavaScript
                                                <span This code is contributed by unknown2108 Python3

Following diagram demonstrates inorder order traversal using threads.

threadedTraversal

Advantages of Threaded Binary Tree

Disadvantages of Threaded Binary Tree

Applications of threaded binary tree –