C-program to delete a node from a tree

10. Write a C program to delete a node from a Binary Search Tree?
Solution:

#include<stdio.h>
struct binarysearchtree{
int data;
struct binarysearchtree* left;
struct binarysearchtree* right;
};
typedef struct binarysearchtree* tree;


tree delete_node(tree T,int num)
{
tree temp;
if (T==NULL)
exit(0);
//return NULL;
else if(num<T->data)
T->left=delete_node(T->left,num);
else if(num>T->data)
T->right=delete_node(T->right,num);
else
{
if(T->left!=NULL&&T->right!=NULL)
{
temp=min(T->right);
T->data=temp->data;
T->right=delete_node(T->right,T->data);
}
else if(T->left==NULL)
{
temp=T;
T=T->right;
}
else if(T->right==NULL)
{
temp=T;
T=T->left;
}
free(temp);
}
return T;
}



Click Here For More Questions

3 comments:

  1. I think you should use (tree* T) instead of (tree T), cause what T=T->right; is doing is just assignment to a local variable.

    ReplyDelete
  2. its now working in the case when node has 2 children!!
    huh!

    ReplyDelete
  3. and yes..its tree * T.

    ReplyDelete