Lecture 34 - Nov 30, 2023
Last lecture
BST (insert and print)
Today
Delete a node in a BST.
Node deletion in BST
class BSTNode {
private:
int value;
*left, *right;
BSTNode
public:
(int v) { value = v; left = right = NULL; }
BSTNode~BSTNode() { delete left; delete right; }
int getValue() { return value; }
*getLeft() { return left; }
BSTNode *getRight() { return right; }
BSTNode void setLeft(BSTNode *l) { left = l; }
void setRight(BSTNode *r) { right = r; }
};
class BSTree {
private:
*root;
BSTNode bool searchNode(int v, BSTNode *n);
void insertHelper(int v, BSTNode *n);
void printInOrderHelper(BSTNode *n);
* minValueNodeHelper(BSTNode *n);
BSTNode
public:
() { root = NULL; }
BSTree~BSTree() { delete root; }
* getRoot() { return root; }
BSTNodebool search(int v);
void insert(int v);
void printInOrder();
* minValueNode();
BSTNode};
* BSTree::minValueNode() {
BSTNodereturn minValueNodeHelper(root);
}
* BSTree::minValueNodeHelper(BSTNode* p) {
BSTNode// p != NULL in case the root is NULL
if (p != NULL && p->getLeft() != NULL) {
return minValueNodeHelper(p->getLeft());
} else {
return p;
}
}
To delete a node in a BST, we have to make sure the properties of a BST are maintained when the node is removed.
- Find the node
- If the node has no children, delete node and update parent node pointer
8
/ \
3 10
/ \ \
1 6 14
/ \ /
4 7 13
For example, nodes 1, 4, 7 and 13.
- If the node has only one subtree, make the parent node point to the parent of the subtree
For example, nodes 10 and 14.
- If the node has two subtrees, replace the node data with the minimum in the right subtree, delete the node with the minimum value in the right subtree
For example, delete 3.
8
/ \
4 10
/ \ \
1 6 14
\ /
7 13
Could 4 have children? Yes, in the right subtree. Delete 4 by calling the delete node function on 4.
8
/ \
4 10
/ \ \
1 6 14
/ \ /
5 7 13
* BSTree::deleteNode(int v, BSTNode* node) {
BSTNodeif (node == NULL) {
return node;
}
if (v < node->getValue()) {
->setLeft(deleteNode(v, node->getLeft()));
node} else if (v > node->getValue()) {
->setRight(deleteNode(v, node->getRight()));
node} else {
// one or no children
if (node->getLeft() == NULL) {
* temp = node->getRight();
BSTNode->setRight(NULL);
nodedelete node;
return temp; // want to put it in the BST back
} else if (node->getRight() == NULL) {
// one child on left
* temp = node->getLeft();
BSTNodedelete node;
return temp; // we want to put it in the BST back
} else {
// node has two children
* temp = minValue(node->getRight());
BSTNode->setValue(temp->getValue());
node// look in the right subtree
->setRight(deleteNode(temp->getValue(), node->getRight()));
node}
}
return node;
}
Trace:
Before
3
/ \
1 6
/ \
4 7
\
5
After
3
/ \
1 6
/ \
5 7