Inorder traversal of a Binary tree is 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).

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 representation of a Threaded Node
Following is C representation of a single threaded node.

struct Node
{
    int data;
    Node *left, *right;
    bool rightThread; 
}

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 Taversal using Threads
Following is C code for inorder traversal in a threaded binary tree.

[pastacode lang=”c” manual=”%2F%2F%20Utility%20function%20to%20find%20leftmost%20node%20in%20atree%20rooted%20with%20n%0Astruct%20Node*%20leftMost(struct%20Node%20*n)%0A%7B%0A%20%20%20%20if%20(n%20%3D%3D%20NULL)%0A%20%20%20%20%20%20%20return%20NULL%3B%0A%20%0A%20%20%20%20while%20(n-%3Eleft%20!%3D%20NULL)%0A%20%20%20%20%20%20%20%20n%20%3D%20n-%3Eleft%3B%0A%20%0A%20%20%20%20return%20n%3B%0A%7D%0A%20%0A%2F%2F%20C%20code%20to%20do%20inorder%20traversal%20in%20a%20threadded%20binary%20tree%0Avoid%20inOrder(struct%20Node%20*root)%0A%7B%0A%20%20%20%20struct%20Node%20*cur%20%3D%20leftmost(root)%3B%0A%20%20%20%20while%20(cur%20!%3D%20NULL)%0A%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20printf(%22%25d%20%22%2C%20cur-%3Edata)%3B%0A%20%0A%20%20%20%20%20%20%20%20%2F%2F%20If%20this%20node%20is%20a%20thread%20node%2C%20then%20go%20to%0A%20%20%20%20%20%20%20%20%2F%2F%20inorder%20successor%0A%20%20%20%20%20%20%20%20if%20(cur-%3ErightThread)%0A%20%20%20%20%20%20%20%20%20%20%20%20cur%20%3D%20cur-%3Eright%3B%0A%20%20%20%20%20%20%20%20else%20%2F%2F%20Else%20go%20to%20the%20leftmost%20child%20in%20right%20subtree%0A%20%20%20%20%20%20%20%20%20%20%20%20cur%20%3D%20leftmost(cur-%3Eright)%3B%0A%20%20%20%20%7D%0A%7D” message=”” highlight=”” provider=”manual”/]

Categorized in: