0% found this document useful (0 votes)
27 views

Void Delete Node

This C++ function deletes a node from a binary search tree. It first checks if the node to delete is a leaf node, and if so directly sets its parent's child pointer to null and deletes the node. If the node has one child, it simply replaces the node with its child. For a node with two children, it finds the rightmost child in the left subtree, copies its value to the node, and deletes that child.

Uploaded by

hcmcity
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Void Delete Node

This C++ function deletes a node from a binary search tree. It first checks if the node to delete is a leaf node, and if so directly sets its parent's child pointer to null and deletes the node. If the node has one child, it simply replaces the node with its child. For a node with two children, it finds the rightmost child in the left subtree, copies its value to the node, and deletes that child.

Uploaded by

hcmcity
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 1

void DeleteNode(struct node*& node) {

if (node->left == NULL) {

struct node* temp = node;


node = node->right;
delete temp;
} else if (node->right == NULL) {

struct node* temp = node;


node = node->left;
delete temp;

} else {
// In-Order predecessor(right most child of left subtree)
// Node has two children - get max of left subtree

struct node** temp = &(node->left); // get left node of the


original node

// find the right most child of the subtree of the left node
while ((*temp)->right != NULL) {
temp = &((*temp)->right);
}

// copy the value from the right most child of left subtree to
the original node
node->value = (*temp)->value;

// then delete the right most child of left subtree since it's
value is
// now in the original node
DeleteNode(*temp);
}
}

You might also like