Tuesday 13 October 2015

BST with parent node (using recursion)

We can also introduce new pointer to the every node i.e. parent node which will store the pointer to the parent node of that node. The parent of root node is null so the parent pointer of root node will point to null in that case and root node is the only node whose pointer is NULL. 
the program is 

#include<stdio.h>

struct node
{
    int key ;
    struct node *parent;
    struct node *left;
    struct node *right;
};
struct node *prev_node=NULL;
typedef struct node* NODE;
void main ()
{
    NODE root = NULL;
    insertion(&root,40);
    insertion(&root,25);
    insertion(&root,70);
    insertion(&root,22);
    insertion(&root,35);
    insertion(&root,60);
    insertion(&root,80);
    insertion(&root,90);
    insertion(&root,10);
    insertion(&root,30);
    deletion(&root,45);
    inorder(root);

}
void insertion(NODE* m,int value)
{
    NODE current= *m;
    NODE temp = (NODE)malloc(sizeof(struct node));
    temp->key= value ;
      temp->left=NULL;
    temp->right=NULL;
     prev_node=current ;
    if (current== NULL)
    {
        *m= temp;
        temp->parent = prev_node;
    }

    else if(current->key > value )
    {
        insertion(&current->left,value);

    }
    else if(current->key <value)
    {
        insertion(&current->right,value);
    }

}

void deletion(NODE **m,int value)
{


    NODE current= *m;
    if (current==NULL)
    {
        printf ("node doesn't exit");
        return;
    }
    if (current->key>value )
    {
          deletion(&current->left,value);

    }
    else if(current->key <value)
    {
        deletion(&current->right,value);
    }

    else
    {
        if((current->left==NULL)&&(current->right==NULL))
        {
            *m==NULL;
            current->parent=NULL;
        }
        else if(current->right==NULL)
        {
            *m=current->left;
            current->left->parent=current->parent;
            current->parent=NULL;    /*optional*/

        }
        else if(current->left==NULL)
        {
            *m= current->right;
            current->right->parent=current->parent;
            current->parent=NULL;
        }
        else
        {
            int next_big = successor(current);
            current->key = next_big;
            deletion(&current->right,next_big); /*that deletion will not recurse as it will terminate in case 1 and 2 above as successor will either be leave node or node with one child */

        }


    }



}

int successor(NODE m )
{
     NODE x= m->right;
    if (x->left!=NULL )
    {
        x=x->left;
    }
    return x;

}

void inorder(NODE m )
{
    if (m==NULL)
    return ;
    else
    {
        inorder(m->left);
        printf("%d\n",m->key);
        inorder(m->right);
    }



}

No comments:

Post a Comment