Deletion of node in Binary Search Tree is throwing error - c

Experts, this is my code of creation and deletion of nodes in Binary Search Tree. It's working fine for insertion, but throwing segmentation fault (core dumped) when trying to delete a node (on invoking deleteNode( ) function). I don't understand what's actually the problem. Please help! Thank you in advance!
#include <stdio.h>
#include <stdlib.h>
int size = 0;
typedef struct mylist{
int data;
struct mylist *left;
struct mylist *right;
}node;
node *root;
void create_root(node *root){
root = NULL;
}
//Inserting nodes
node* insert(node *root, int val){
node *ptr, *parentptr, *nodeptr;
ptr = (node*)malloc(sizeof(node));
ptr -> data = val;
ptr -> left = NULL;
ptr -> right = NULL;
if(root == NULL)
root = ptr;
else{
parentptr = NULL;
nodeptr = root;
while(nodeptr != NULL){
parentptr=nodeptr;
if(val < nodeptr -> data)
nodeptr = nodeptr -> left;
else
nodeptr = nodeptr -> right;
}
if(val < parentptr -> data)
parentptr -> left = ptr;
else
parentptr -> right = ptr;
}
return root;
}
node* minValueNode(node* root)
{
node* cur = root;
while (cur->left != NULL)
cur = cur->left;
return cur;
}
node* deleteNode(node* root, int key)
{
if (root == NULL){
printf("\nValue not found\n");
}
if (key < root-> data)
root->left = deleteNode(root->left, key);
else if (key > root-> data)
root->right = deleteNode(root->right, key);
else
{
if (root->left == NULL)
{
node *temp = root->right;
free(root);
return temp;
}
else if (root->right == NULL)
{
node *temp = root->left;
free(root);
return temp;
}
node* temp = minValueNode(root->right); //Inorder successor
root->data = temp->data;
root->right = deleteNode(root->right, temp->data);
}
return root;
}
void main(){
int option, val;
node *ptr;
int flag = 1;
create_root(root);
while(flag != 2){
printf("\nChoose-\n1-Insert\n2-Delete\n3-Exit\n");
scanf("%d", &option);
switch(option){
case 1:{
printf("\nEnter the value of new node\n");
size++;
scanf("%d", &val);
root = insert(root, val);
break;
}
case 2:{
int k;
printf("Enter the value to delete");
scanf("%d",&k);
root=deleteNode(root, k);
size--;
break;
}
case 3:
flag=2;
break;
default:
printf("\nWrong entry\n");
}
}
}

You must either return NULL in the first if() in deleteNode(), or you must put an else before the second if()
node* deleteNode(node* root, int key)
{
if (root == NULL){
printf("\nValue not found\n");
return NULL; // <== This was missing.
}
...
}
or alternatively (perhaps intended?):
node* deleteNode(node* root, int key)
{
if (root == NULL){
printf("\nValue not found\n");
}
else if(key < root->data)
...
}
At the moment this falls through to the next if(key < root->data) even when root is null, which causes the segfault.
Also: Use nullptr if you can use C++11.

Related

BST - Deleting a Node

so I'm trying to solve a problem from log2base2.com involving deleting a node from BST. It works except when trying to delete a node with two children. I know I could simply replace the numbers and then delete the duplicate at the end, but what if my struct has more data than just key? So what am I doing wrong please?
#include<stdio.h>
#include<stdlib.h>
struct node
{
int key;
struct node *left;
struct node *right;
};
int getRightMin(struct node *root)
{
//Write your code here
struct node *temp = root;
while(temp->left!=NULL)
{
temp=temp->left;
}
return temp;
}
struct node *removeNode(struct node *root, int key)
{
//Write your code here
if(root == NULL){return NULL;}
if(key<root->key){root->left = removeNode(root->left, key);}
else if(key>root->key){root->right = removeNode(root->right,key);}
else
{
if(root->left==NULL && root->right==NULL)
{
free(root);
return NULL;
}
else if(root->left)
{
struct node *temp = root->left;
free(root);
return temp;
}
else if(root->right)
{
struct node *temp = root->right;
free(root);
return temp;
}
else
{
struct node *temp = getRightMin(root->right);
temp->left = root->left;
temp->right = root->right;
root = temp;
root->right = removeNode(root->right, temp->key);
}
}
return root;
}
//Don't change the below code
struct node *getNewNode(int val)
{
struct node *newNode = malloc(sizeof(struct node));
newNode->key = val;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
struct node *insert(struct node *root, int val)
{
if(root == NULL)
return getNewNode(val);
if(root->key < val)
root->right = insert(root->right,val);
else if(root->key > val)
root->left = insert(root->left,val);
return root;
}
void inorder(struct node *root)
{
if(root == NULL)
return;
inorder(root->left);
printf("%d ",root->key);
inorder(root->right);
}
int main()
{
struct node *root = NULL;
root = insert(root,100);
root = insert(root,50);
root = insert(root,200);
root = insert(root,150);
root = insert(root,300);
int key;
scanf("%d",&key);
root = removeNode(root,key);
inorder(root);
return 0;
}
TEST CASE 1:
INPUT: 200
EXPECTED OUTPUT: 50 100 150 300
ACTUAL OUTPUT: 50 100 150
TEST CASE 2:
INPUT: 100
EXPECTED OUTPUT: 50 150 200 300
ACTUAL OUTPUT: 50
You have to reorder conditional in removeNode() to:
if(root->left==NULL && root->right==NULL)
{
free(root);
return NULL;
}
else if (root->left && root->right)
{
struct node *temp = getRightMin(root->right);
temp->left = root->left;
temp->right = root->right;
root = temp;
root->right = removeNode(root->right, temp->key);
}
else if(root->left)
{
struct node *temp = root->left;
free(root);
return temp;
}
else // root->right != NULL
{
struct node *temp = root->right;
free(root);
return temp;
}
It looks that (root->left && root->right) case was caught by (root->left) and
reference to root->right was lost.

Why does my binary tree search function not return the root adress?

I'm sorry for asking too much, so this is almost the same with my previous questions.
I have a balancing binary tree code with deletion function, so the problem is in my searchdelete() function. I don't know why it won't return the root back. So for example
5, 4, 3, 2, 1
And then i input on the menu "Data to be deleted: 1"
it goes to the searchdelete(); function, and then it successfully
shows that the data is found, found = 1
but after that, it just won't return the root address. I have no idea why it won't return.
So in the Delete(); function, it wont print the printf("root after = %d", root->data)
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<conio.h>
struct node{
int data, balance;
struct node *left, *right;
};
int insert(struct node **root, struct node **curr, int data){
struct node *newNode = (struct node*)malloc(sizeof(struct node));
newNode -> data = data;
newNode -> left = NULL;
newNode -> right = NULL;
newNode -> balance = 0;
if((*root) == NULL){
(*root) = (*curr) = newNode;
(*root) -> left = NULL;
(*root) -> right = NULL;
return 0;
} else {
if((*curr)->left == NULL && (*curr)->balance == 0){
(*curr) -> balance = (*curr) -> balance - 1;
(*curr) -> left = newNode;
return 0;
} else if ((*curr)->right == NULL && (*curr)->balance == -1){
(*curr) -> balance = (*curr) -> balance + 1;
(*curr) -> right = newNode;
return 0;
} else if ((*curr)->balance == 0 && (*curr)->left->balance == 0){
(*curr) -> balance = (*curr) -> balance - 1;
(*curr) = (*curr)->left;
return insert(root,curr,data);
} else if ((*curr)->balance < 0 && (*curr)->left->balance < 0){
(*curr) -> balance = (*curr) -> balance - 1;
(*curr) = (*curr) -> left;
return insert(root,curr,data);
} else if ((*curr)->balance < 0 && (*curr)->left->balance == 0){
(*curr) -> balance = (*curr) -> balance + 1;
(*curr) = (*curr)->right;
return insert(root, curr, data);
}
}
}
void preorder(struct node *root){
if(root == NULL) return;
printf("%d ", root->data);
preorder(root->left);
preorder(root->right);
}
void postorder(struct node *root){
if(root == NULL) return;
postorder(root->left);
postorder(root->right);
printf("%d ", root->data);
}
void inorder(struct node *root){
if(root == NULL) return;
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
void search(struct node *root, int *key, int *found){
if(root == NULL) return;
search(root->left, key, found);
if(root->data == *key){
*found = 1;
return ;
}
search(root->right, key, found);
}
struct node *findMin(struct node *root){
while(root->left != NULL) root = root->left;
return root;
}
struct node *searchdelete(struct node *root, int data){
if(root == NULL) return root; //This is the searchdelete
searchdelete(root->left, data);
if(root->data == data){
printf("found = %d", root->data);
return root;
}
searchdelete(root->right, data);
}
struct node *Delete(struct node *root, int data){
printf("root before = %d\n", root->data);
if(root == NULL) return root;
else if(data != root->data) {
root = searchdelete(root, data);
printf("root after = %d\n", root->data); //this is where it won't print
system("pause");
}
else{
//Case 1: no child / leaf node
if(root->left == NULL && root->right == NULL){
printf("NULL\n");
free(root);
root = NULL;
}
//Case 2: one child, left or right
else if(root->left == NULL){
printf("left null\n");
struct node *temp = root;
root = root->right;
free(temp);
} else if (root->right == NULL){
printf("right null\n");
struct node *temp = root;
root = root->left;
free(temp);
}
//Case 3: two children
else{
printf("two children \n");
if(root->right->data > root->data){
struct node *temp = root;
root = root->right;
free(temp);
} else {
struct node *temp = root;
root = root->left;
free(temp);
}
}
}
system("pause");
return root;
}
int main(){
struct node *root, *curr;
int choice, data, key, found, delKey;
root = curr = NULL;
while(1){
found = 0;
printf("Balanced Binary Tree Menu\n");
printf("1. Insert Data\n");
printf("2. View on pre order\n");
printf("3. View on post order\n");
printf("4. View on in order\n");
printf("5. Search\n");
printf("6. Delete\n");
printf("7. Exit\n");
printf("Pilihan: ");scanf("%d", &choice);fflush(stdin);
if(choice == 1){
printf("Enter data : "); scanf("%d", &data);
curr = root;
insert(&root, &curr, data);
} else if (choice == 2){
preorder(root);
system("pause");
} else if (choice == 3){
postorder(root);
system("pause");
} else if (choice == 4){
inorder(root);
system("pause");
} else if (choice == 5){
printf("Search: "); scanf("%d", &key);
search(root, &key, &found);
if(found == 1){
printf("Data found !\n");
} else {
printf("Data not found !\n");
}
system("pause");
} else if (choice == 6){
printf("Enter data to be deleted: "); scanf("%d", &delKey);
Delete(root, delKey);
} else if (choice == 7){
return 1;
}
system("cls");
}
return 0;
}
Why does my binary tree search function not return the root adress?
I have no idea why it won't return.
because 2 return are missing
Can be:
struct node * searchdelete(struct node *root, int data){
if(root == NULL)
return root;
if(root->data == data){
printf("found = %d", root->data); /* debug, to be removed */
return root;
}
if ((root = searchdelete(root->left, data)) != NULL)
return root;
return searchdelete(root->right, data);
}
In search why key is an int* rather than just an int like for searchdelete ? For me he function search is useless, searchdelete is already enough to know if the key is present in the tree just calling it and comparing its return value with NULL. So better to remove search and to rename searchdelete to be search (or find)
In both functions you search without using the fact the tree can be sorted, I mean on the left the data are less, on the right they are greater, that improves the performance
There is no interest at all to have a binary tree if the elements are randomly placed in
Your definition of Delete has a lot of problems, including undefined behavior because you free cells without removing them from the tree

Insertion failure in a Binary Search Tree

Here is my code for the creation and insertion of the binary search tree
struct BTNode
{
int info;
struct BTNode *left, *right;
};
struct BTNode* create(int data)
{
struct BTNode *root;
struct BTNode *n = malloc(sizeof(struct BTNode));
n->info = data;
n->left = NULL;
n->right = NULL;
root = n;
return(root);
}
struct BTNode* insert(struct BTNode *root, int data)
{
struct BTNode *ptr;
struct BTNode *n = malloc(sizeof(struct BTNode));
if (n == NULL)
printf("\nOUT OF MEMORY!\n");
n->info = data;
n->left = NULL;
n->right = NULL;
ptr = root;
while (ptr != NULL){
if (data < ptr->info){
if (ptr->left == NULL)
ptr->left = n;
ptr = ptr->left;
}
else if (data > ptr->info){
if (ptr->right == NULL)
ptr->right = n;
ptr = ptr->right;
}
}
return(n);
}
and here is the main() function
int main()
{
struct BTNode *root = NULL;
int choice, data;
printf("\nWrite the root data: ");
scanf("%d", &data);
root = create(data);
while (1){
printf("\n1.Insert 2.Preorder 3.Exit\n");
scanf("%d", &choice);
switch(choice){
case 1:
printf("\nWrite the data: ");
scanf("%d", &data);
insert(root, data);
break;
I am able to create the root node but whenever I am trying to insert the data, I give my data and the compiler stops doing anything. Any idea why this is happening?
Your while() loop goes on forever because you keep going even after you find a place to insert the node:
while(ptr!=NULL){
if(data<ptr->info){
if(ptr->left==NULL)
ptr->left=n;
ptr=ptr->left;
}
else if(data>ptr->info){
if(ptr->right==NULL)
ptr->right=n;
ptr=ptr->right;
}
}
You need to break out of the while() loop after inserting the node:
while (ptr != NULL) {
if (data < ptr->info) {
if (ptr->left == NULL) {
ptr->left = n;
break;
}
ptr = ptr->left;
} else if (data > ptr->info) {
if (ptr->right == NULL) {
ptr->right = n;
break;
}
ptr = ptr->right;
}
}
Also, bonus points for checking if malloc() fails
struct BTNode *n = malloc(sizeof(struct BTNode));
if (n == NULL)
printf("\nOUT OF MEMORY!\n");
But negative points for simply continuing on anyway, you should exit the function if malloc() fails
struct BTNode *n = malloc(sizeof(struct BTNode));
if (n == NULL) {
printf("\nOUT OF MEMORY!\n");
return NULL:
}
And then of course, the code calling insert() should know what to do if insert() returns NULL.

Delete function in Binary Tree in C

I'm writing the basic functions for binary tree and everything seems to compile and run, but when i try to use my delete function it doesn't do anything.
After executing i get the same sequence of numbers, so i'm trying to figure out what's wrong with the Delete function, is it logically correct?
#include <stdio.h>
#include <stdlib.h>
typedef struct treeNode
{
int data;
struct treeNode *left;
struct treeNode *right;
}treeNode;
treeNode *Insert(treeNode *node, int data)
{
if(node == NULL)
{
treeNode *temp;
temp = malloc(sizeof(treeNode));
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
if(data > (node->data))
{
node->right = Insert(node->right, data);
}
else if(data < (node->data))
{
node->left = Insert(node->left, data);
}
return node;
}
treeNode *Delete(treeNode *node, int data)
{
if(node == NULL)
{
printf("element not found\n");
}
else if(data < node->data)
{
node->left = Delete(node->left, data);
}
else if(data > node->data)
{
node->right = Delete(node->right, data);
}
return node;
}
treeNode *Find(treeNode *node, int data)
{
if(node == NULL)
{
return NULL;
}
if(data > node->data)
{
return Find(node->right, data);
}
else if(data < node->data)
{
return Find(node->left, data);
}
else
{
return node;
}
}
void Print(treeNode *node)
{
if(node == NULL)
{
return;
}
Print(node->left);
printf("%d", node->data);
Print(node->right);
}
int main()
{
treeNode *root = NULL;
root = Insert(root, 5);
root = Insert(root, 8);
root = Insert(root, 6);
root = Insert(root, 4);
root = Insert(root, 3);
root = Insert(root, 9);
root = Insert(root, 10);
root = Insert(root, 19);
Print(root);
printf("\n");
root = Delete(root, 5);
root = Delete(root, 8);
Print(root);
printf("\n");
treeNode *temp;
temp = Find(root, 8);
if(temp == NULL)
{
printf("Element 8 not found\n");
}
else
{
printf("Element 8 found\n");
}
temp = Find(root, 5);
if(temp == NULL)
{
printf("element 5 not found\n");
}
else
{
printf("element 5 found\n");
}
}
Basically i was only replacing the node with itself, but this can be solved by replacing the deleted node with the minimum element in the right subtree or the maximum element in the left subtree.
The function that works:
treeNode * Delete(treeNode *node, int data)
{
treeNode *temp;
if(node==NULL)
{
printf("Element Not Found");
}
else if(data < node->data)
{
node->left = Delete(node->left, data);
}
else if(data > node->data)
{
node->right = Delete(node->right, data);
}
else
{
/* Now We can delete this node and replace with either minimum element
in the right sub tree or maximum element in the left subtree*/
if(node->right && node->left)
{
/* Here we will replace with minimum element in the right sub tree */
temp = FindMin(node->right);
node -> data = temp->data;
/* As we replaced it with some other node, we have to delete that node */
node -> right = Delete(node->right,temp->data);
}
else
{
/* If there is only one or zero children then we can directly
remove it from the tree and connect its parent to its child */
temp = node;
if(node->left == NULL)
node = node->right;
else if(node->right == NULL)
node = node->left;
free(temp); /* temp is longer required */
}
}
return node;
}

Nonrecursive/Iterative Binary Search Tree in C (Homework)

How can I create/delete a node in a Binary Search Tree using Iterative Algorithm in C?
Iterative insertion:
struct tree_node *Insert_Element (struct tree_node *root, void *key, void *data) {
struct tree_node *new_node, *node;
node = root;
do {
switch (compare(key, node->key)) {
case -1: {
if (node->left == NULL) {
if ((new_node = create_node(key, data)) == NULL) {
return NULL;
}
node->left = new_node;
return new_node;
}
node = node->left;
} break;
case 1: {
if (node->right == NULL) {
if ((new_node = create_node(key, data)) == NULL) {
return NULL;
}
node->right = new_node;
return new_node;
}
node = node->right;
} break;
default: {
return node;
}
}
} while (node != NULL);
return NULL;
}
Iterative insertion & deletion in BST
struct bst {
int data;
struct bst *left;
struct bst *right;
};
typedef struct bst bst_t;
bst_t *get_new_node(int val)
{
bst_t *node = (bst_t *) malloc(sizeof(bst_t));
node->data = val;
node->left = NULL;
node->right= NULL;
return node;
}
bst_t *insert(bst_t *root, int val)
{
if(!root) return get_new_node(val);
bst_t *prev = NULL, *ptr = root;
char type = ' ';
while(ptr) {
prev = ptr;
if(val < ptr->data) {
ptr = ptr->left;
type = 'l';
} else {
ptr = ptr->right;
type = 'r';
}
}
if(type == 'l')
prev->left = get_new_node(val);
else
prev->right = get_new_node(val);
return root;
}
int find_minimum_value(bst_t *ptr)
{
int min = ptr ? ptr->data : 0;
while(ptr) {
if(ptr->data < min) min = ptr->data;
if(ptr->left) {
ptr = ptr->left;
} else if(ptr->right) {
ptr = ptr->right;
} else ptr = NULL;
}
return min;
}
bst_t *delete(bst_t *root, int val)
{
bst_t *prev = NULL, *ptr = root;
char type = ' ';
while(ptr) {
if(ptr->data == val) {
if(!ptr->left && !ptr->right) { // node to be removed has no children's
if(ptr != root && prev) { // delete leaf node
if(type == 'l')
prev->left = NULL;
else
prev->right = NULL;
} else root = NULL; // deleted node is root
} else if (ptr->left && ptr->right) { // node to be removed has two children's
ptr->data = find_minimum_value(ptr->right); // find minimum value from right subtree
val = ptr->data;
prev = ptr;
ptr = ptr->right; // continue from right subtree delete min node
type = 'r';
continue;
} else { // node to be removed has one children
if(ptr == root) { // root with one child
root = root->left ? root->left : root->right;
} else { // subtree with one child
if(type == 'l')
prev->left = ptr->left ? ptr->left : ptr->right;
else
prev->right = ptr->left ? ptr->left : ptr->right;
}
}
free(ptr);
}
prev = ptr;
if(val < ptr->data) {
ptr = ptr->left;
type = 'l';
} else {
ptr = ptr->right;
type = 'r';
}
}
return root;
}
Nice post. Just a suggestion. I believe, finding a minimum value in a BST doesn't have to traverse the right subtree. Minimum value must be either on the left subtree or node itself(in case if left subtree is null). Function find_minimum_value can be optimized if right subtree traversal is removed.
int find_minimum_value(bst_t *ptr)
{
while(ptr->left) {
ptr = ptr->left;
}
return ptr->data;
}
In C, you can cast the pointers in the tree to intptr_t type and perform bitwise operations to them.
As you traverse down the tree, you can store the 'parent' pointer of a node by xoring it with the pointer you traversed with. You can then traverse back up the tree by xoring the the address of the node you are coming from with the modified pointer.
A worked example of this traditional technique is at http://sites.google.com/site/debforit/efficient-binary-tree-traversal-with-two-pointers
Given the ability to traverse the tree without recursion, you can then create iterative versions of any of the algorithms based on traversing the tree.

Resources