#include <iostream>
using namespace std;
struct Node {
int val;
Node* left;
Node* right;
Node(int v) : val(v), left(nullptr), right(nullptr) {}
};
Node* findMin(Node* root) {
while (root && root->left) {
root = root->left; // advance to leftmost node
}
return root;
}
Node* deleteNode(Node* root, int key) {
if (!root) return nullptr; // base case: empty tree
if (key < root->val) {
root->left = deleteNode(root->left, key); // go left to find key
} else if (key > root->val) {
root->right = deleteNode(root->right, key); // go right to find key
} else {
// found node to delete
if (!root->left) {
Node* temp = root->right; // no left child, replace with right
delete root;
return temp;
} else if (!root->right) {
Node* temp = root->left; // no right child, replace with left
delete root;
return temp;
} else {
// two children: find inorder successor
Node* temp = findMin(root->right); // smallest in right subtree
root->val = temp->val; // copy successor value
root->right = deleteNode(root->right, temp->val); // delete successor
}
}
return root;
}
void inorderPrint(Node* root) {
if (!root) return;
inorderPrint(root->left);
cout << root->val << " ";
inorderPrint(root->right);
}
int main() {
Node* root = new Node(5);
root->left = new Node(3);
root->right = new Node(7);
root->left->left = new Node(2);
root->left->right = new Node(4);
root->right->right = new Node(8);
cout << "Original BST inorder: ";
inorderPrint(root);
cout << "\n";
root = deleteNode(root, 3);
cout << "BST inorder after deleting 3: ";
inorderPrint(root);
cout << "\n";
return 0;
}
if (!root) return nullptr; // base case: empty tree
stop recursion if tree/subtree is empty
if (key < root->val) {
root->left = deleteNode(root->left, key); // go left to find key
}
search left subtree if key is smaller
else if (key > root->val) {
root->right = deleteNode(root->right, key); // go right to find key
}
search right subtree if key is larger
if (!root->left) {
Node* temp = root->right; // no left child, replace with right
delete root;
return temp;
}
delete node with no left child by replacing with right child
else if (!root->right) {
Node* temp = root->left; // no right child, replace with left
delete root;
return temp;
}
delete node with no right child by replacing with left child
Node* temp = findMin(root->right); // smallest in right subtree
root->val = temp->val; // copy successor value
root->right = deleteNode(root->right, temp->val); // delete successor
replace node with inorder successor and delete successor
Original BST inorder: 2 3 4 5 7 8
BST inorder after deleting 3: 2 4 5 7 8