Leetcode 450. Delete Node in a BST
Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST.
0
to 10^4
.Here is the C++ code to solve the problem:
#include <iostream>
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
if (!root) return root;
if (key < root->val) {
root->left = deleteNode(root->left, key);
} else if (key > root->val) {
root->right = deleteNode(root->right, key);
} else {
// Node with only one child or no child
if (!root->left) {
TreeNode* temp = root->right;
delete root;
return temp;
} else if (!root->right) {
TreeNode* temp = root->left;
delete root;
return temp;
}
// Node with two children: Get the inorder successor (smallest in the right subtree)
TreeNode* temp = minValueNode(root->right);
root->val = temp->val;
root->right = deleteNode(root->right, temp->val);
}
return root;
}
private:
TreeNode* minValueNode(TreeNode* node) {
TreeNode* current = node;
while (current && current->left) {
current = current->left;
}
return current;
}
};
int main() {
Solution solution;
// Example usage:
// Constructing a BST
TreeNode* root = new TreeNode(5);
root->left = new TreeNode(3);
root->right = new TreeNode(6);
root->left->left = new TreeNode(2);
root->left->right = new TreeNode(4);
root->right->right = new TreeNode(7);
// Deleting a node
int key = 3;
root = solution.deleteNode(root, key);
std::cout << "Root after deletion: " << root->val << std::endl; // Expected output root node value
// Clean up memory
// Proper tree deletion code should be added here to handle resources.
return 0;
}
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?