Skip to main content

Threaded Binary Trees

You can download the complete program from here
 
Binary trees need to be traversed using recursion. All the three methods of traversal - inorder, preorder and post order methods employ recursion.

Recursion needs stack storage. In cases where the tree is highly unbalanced, the cost on this traversal would be high.

It would be nice where one could traverse a binary tree without using recursion.

That is where a threaded tree comes into picture. This utilizes the pointers which are wasted on leaf nodes and uses these to save threads pointing to inorder successor or inorder predecessor.

In the diagram above, node A does not have right child. Instead of NULL, a link to B is stored in A->right. Remember that B is the inorder successor of A. Similarly C does not have child nodes. So it has link to predecessor B as left thread and link to D as right thread.

Only A has left link as NULL because A has no predecessor. And I has no successor, so it has right link as NULL.

Types of threaded binary tree

A threaded binary tree can be single or double. A single threaded tree will have either in order successor for   nodes which do  not have a right children or in order predecessor for  nodes which do not have a left children. But not both.

Whereas a double threaded binary tree will have a thread for in order successor, and another thread for in order predecessor whenever a node does not have a left and right child nodes.

The diagram shown above is a double threaded binary tree.

Structure of threaded binary tree node


To differentiate between a thread and a link to child, a boolean is  used. So the threaded tree node will have two extra fields. I have called them  isleftthread and isrightthread. If isleftthread is 1, node->left is a thread to in order successor and it is not a link to child node. But if this value is 0, node->left is a link to left child.

Similarly if node->isrightthread is 1, node->right is a thread. If it is 0, node->right is a child node link.

struct node
{
    int val;
    struct node *left;
    struct node *right;
    int isleftthread;
    int isrightthread;
};


To insert a node into such a tree, you need to do the following
  1. node = root
  2. if node->val > key value, branch to left 
  3. if node->val <key value,  branch to right
  4. Repeat 2 to 3 until you  get a thread (thread means there is no child node present. which means we can insert the new node there)
  5. link the parent to newnode
  6. if newnode is right child of parent
    1. set newnode->right as parent->right (thread)
    2. set newnode->left as parent (thread)
    3. set parent->right as newnode (child)
    4. set parent->isrightthread as 0(false)
  7. if newnode is left child of parent
    1. set newnode->left as parent->left (thread)
    2. set newnode->right as parent (thread)
    3. set parent->left as newnode (child)
    4. set parent->isleftthread as 0(false)
Here is the C code for insert a value into threaded binary tree

NODEPTR insert_node(NODEPTR nd,NODEPTR newnode)
{
     NODEPTR parent = nd;
     NODEPTR root = nd;
     if(root == NULL)
        return newnode;
     while(nd!=NULL)
     {
 
        parent = nd;
        if(newnode->val > nd->val)
        {
        if(nd->isrightthread)
        {
           nd = nd->right;
           break;
         }
        else
           nd = nd->right; 
     }
  
    else if(newnode->val <nd->val){
        if(nd->isleftthread)
        {
          nd = nd->left;
          break;
        }
        else
                 nd = nd->left;
     }
        else
            {
              printf("Duplicate values not allowed");
              return NULL;
            }
     }

Next let us see how we can traverse such a threaded binary tree in order without using recursion.

  1. Traverse to the left most node and find the minimum of the tree.
  2. From this node, use the right link to traverse. 
  3. Repeat until NULL is encountered. 
And here is the code for inorder traversal of threaded binary tree.

void in_order(NODEPTR nd)
{
    /* find extreme left node*/
    while(!nd->isleftthread)
 nd = nd->left;
   /* traverse all nodes till extreme right end*/
    while(nd)
 {
   printf("%d  ",nd->val);
   if(nd->isrightthread)
             nd = nd->right;
          else 
            {
              nd = nd->right;
              while(nd!=NULL && !nd->isleftthread)
                nd = nd->left;
           }
 } 
}
Now we are ready to write the complete program.


#include<stdio.h>
#include<stdlib.h>
struct node
{
   int val;
   struct node *left;
   struct node *right;
   int isleftthread;
   int isrightthread;
};
typedef struct node *NODEPTR;

NODEPTR create_node(int num)
{
     NODEPTR temp = (NODEPTR)malloc(sizeof(struct node));
     temp->val = num;
     temp->left = NULL;
     temp->right = NULL;
     temp->isleftthread = 1;
     temp->isrightthread = 1;
     return temp;
}

NODEPTR insert_node(NODEPTR nd,NODEPTR newnode)
{
     NODEPTR parent = nd;
     NODEPTR root = nd;
     if(root == NULL)
        return newnode;
     while(nd!=NULL)
     {
 
 parent = nd;
        if(newnode->val > nd->val)
  {
    if(nd->isrightthread)
   {
   nd = nd->right;
   break;
  }
  else
   nd = nd->right; 
   }
  
        else if(newnode->val <nd->val){
         if(nd->isleftthread)
   {
   nd = nd->left;
   break;
   }
  else
                 nd = nd->left;
  }
        else
            {
  printf("Duplicate values not allowed");
  return NULL;
            }
     }
     if(newnode->val >parent->val)
 {
 newnode->right = parent->right;
 parent->right = newnode;
 parent->isrightthread=0;
 newnode->left = parent;
 }
     else
 {
 newnode->left = parent->left;
  parent->left = newnode;
 parent->isleftthread = 0;
 newnode->right = parent;
 }
     return root;
}
void in_order(NODEPTR nd)
{
    /* find extreme left node*/
    while(!nd->isleftthread)
 nd = nd->left;
   /* traverse all nodes till extreme right end*/
    while(nd)
 {
   printf("%d  ",nd->val);
   if(nd->isrightthread)
             nd = nd->right;
          else 
            {
              nd = nd->right;
              while(nd!=NULL && !nd->isleftthread)
                nd = nd->left;
           }
 } 
}

void pre_order(NODEPTR nd)
{
   if(nd!=NULL)
    {
        printf("%d---",nd->val);   
        pre_order(nd->left);
        pre_order(nd->right);
            
     }
} 
 
int main()
{
       NODEPTR root=NULL,delnode; 
       int n;
       do
       {
           NODEPTR newnode;
           printf("Enter value of node(-1 to exit):");
           scanf("%d",&n);
           if(n!=-1)
            {  
               newnode = create_node(n);
               root = insert_node(root,newnode);
             }
       } while (n!=-1);
       
       printf("\nInorder traversal\n");
       in_order(root);   
       return 0;
}

Comments

Popular posts from this blog

Linked list in C++

A linked list is a versatile data structure. In this structure, values are linked to one another with the help of addresses. I have written in an earlier post about how to create a linked list in C.  C++ has a library - standard template library which has list, stack, queue etc. data structures. But if you were to implement these data structures yourself in C++, how will you implement? If you just use new, delete, cout and cin, and then claim it is your c++ program, you are not conforming to OOPS concept. Remember you have to "keep it together". Keep all the functions and variables together - in a class. You have to have class called linked list in which there are methods - append, delete, display, insert, find, find_last. And there will also be a data - head. Defining node We need a structure for all these nodes. A struct can be used for this purpose, just like C. struct node { int val; struct node * next; }; Next we need to define our class. W

Swap nodes of a linked list

Qn: Write a function to swap the adjacent nodes of a singly linked list.i.e. If the list has nodes as 1,2,3,4,5,6,7,8, after swapping, the list should be 2,1,4,3,6,5,8,7 Image from: https://tekmarathon.com Though the question looks simple enough, it is tricky because you don't just swap the pointers. You need to take care of links as well. So let us try to understand how to go about it. Take two adjacent nodes p1 and p2 Let prevnode be previous node of p1 Now link prevnode to p2 Link p2 to p1 Link p1 to next node of p2 So the code will be prevnode -> next = p2; p1 -> next = p2 -> next; p2 -> next = p1; But what about the start node or head? head node does not have previous node If we swap head with second node, modified head should be sent back to caller  To take care of swapping first and second nodes, we can write p1 = head; p2 = head -> next; p1 -> next = p2 -> next; p2 -> next = p1; head = p2;  Now we are read

Binary tree deletion - non-recursive

In the previous post we have seen how to delete a node of a binary search tree using recursion. Today we will see how to delete a node of BST using a non-recursive function. Let us revisit the 3 scenarios here Deleting a node with no children just link the parent to NULL Deleting a node with one child link the parent to  non-null child of node to be deleted Deleting a node with both children select the successor of node to be deleted copy successor's value into this node delete the successor In order to start, we need a function to search for a node in binary search tree. Did you know that searching in  a BST is very fast, and is of the order O(logn). To search Start with root Repeat until value is found or node is NULL If the search value is greater than node branch to right If the search value is lesser than node branch to left.  Here is the function NODEPTR find_node (NODEPTR root,NODEPTR * parent, int delval) { NODEPTR nd = root; NODEPTR pa = root; if (root -> v