0% found this document useful (0 votes)
6 views1 page

Delete BST

The provided code implements a function to delete a node from a binary search tree based on a given key. It handles three cases: deleting a leaf node, deleting a node with one child, and deleting a node with two children by replacing it with its inorder successor. A helper function is included to find the minimum value node in a subtree.

Uploaded by

zohaibsaeed1701
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views1 page

Delete BST

The provided code implements a function to delete a node from a binary search tree based on a given key. It handles three cases: deleting a leaf node, deleting a node with one child, and deleting a node with two children by replacing it with its inorder successor. A helper function is included to find the minimum value node in a subtree.

Uploaded by

zohaibsaeed1701
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

Node* deleteNode(Node* root, int key) {

// Base case: If the tree is empty


if (root == NULL) {
return NULL;
}

// Traverse the tree to find the node to delete


if (key < root->data) {
root->left = deleteNode(root->left, key);
} else if (key > root->data) {
root->right = deleteNode(root->right, key);
} else {
// Node to delete found
// Case 1: Node has no children (leaf node)
if (root->left == NULL && root->right == NULL) {
delete root;
return NULL;
}

// Case 2: Node has one child


if (root->left == NULL) {
Node* temp = root->right;
delete root;
return temp;
} else if (root->right == NULL) {
Node* temp = root->left;
delete root;
return temp;
}

// Case 3: Node has two children


// Find the inorder successor (smallest in the right subtree)
Node* temp = findMin(root->right);
root->data = temp->data; // Replace the current node's data with the
successor's data
root->right = deleteNode(root->right, temp->data); // Delete the successor
node
}

return root;
}

// Helper function to find the minimum value node in a subtree


Node* findMin(Node* root) {
while (root->left != NULL) {
root = root->left;
}
return root;
}

You might also like