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 is structure of a single-threaded binary tree.
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.
Inorder traversal of created threaded tree is 4 2 5 1 6 3 7
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