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. 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.
link brightness_4 code
Node *left, *right;
// Used to indicate whether the right pointer is a normal right
// pointer or a pointer to inorder successor.
How to convert a Given Binary Tree to Threaded Binary Tree?
We have discussed a Queue-based solution here. In this post, space-efficient solution is discussed that doesn’t require a queue.
The idea is based on the fact that we link from inorder predecessor to a node. We link those inorder predecessor which lie in subtree of node. So we find inorder predecessor of a node if its left is not NULL. Inorder predecessor of a node (whose left is NULL) is a rightmost node in the left child. Once we find the predecessor, we link a thread from it to the current node.
Following is the implementation of the above idea.
Inorder traversal of created threaded tree is
4 2 5 1 6 3 7
This algorithm works in O(n) time complexity and O(1) space other than function call stack.
This article is contributed by Gopal Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.