Sponsored
Sponsored
This approach involves traversing the tree recursively to find the node to be deleted. Once found, we handle it based on different cases: the node has no children, one child, or two children. For the two children case, replace the node with its inorder successor (minimum of the right subtree).
Time Complexity: O(h), where h is the height of the tree.
Space Complexity: O(h) due to recursion stack space.
1TreeNode* deleteNode(TreeNode* root, int key) {
2 if (root == NULL) return root;
3 if (key < root->val) {
4 root->left = deleteNode(root->left, key);
5 } else if (key > root->val) {
6 root->right = deleteNode(root->right, key);
7 } else {
8 if (root->left == NULL) {
9 TreeNode* temp = root->right;
10 free(root);
11 return temp;
12 } else if (root->right == NULL) {
13 TreeNode* temp = root->left;
14 free(root);
15 return temp;
16 }
17 TreeNode* temp = minValueNode(root->right);
18 root->val = temp->val;
19 root->right = deleteNode(root->right, temp->val);
20 }
21 return root;
22}
23
24TreeNode* minValueNode(TreeNode* node) {
25 TreeNode* current = node;
26 while (current && current->left != NULL) {
27 current = current->left;
28 }
29 return current;
30}
The function deleteNode
recursively searches for the node with the provided key. If found, the node is deleted based on the number of its children. If the node has two children, it is replaced with its inorder successor.
This method uses an iterative approach with a stack to traverse and manipulate the binary search tree. By applying the concept of replacing with the inorder successor, this method ensures the tree's properties remain intact after deletion.
Time Complexity: O(h), where h is tree height.
Space Complexity: O(1) since no additional data structures are used.
1TreeNode* deleteNode(TreeNode* root, int key) {
TreeNode** cur = &root, **back = nullptr;
while (*cur && (*cur)->val != key)
cur = key < (*cur)->val ? &(*cur)->left : &(*cur)->right;
if (*cur) removeNode(cur);
return root;
}
void removeNode(TreeNode** node) {
TreeNode* toDelete = *node;
if (!(*node)->left)
*node = (*node)->right;
else if (!(*node)->right)
*node = (*node)->left;
else {
TreeNode** successor = &(*node)->right;
while ((*successor)->left) successor = &(*successor)->left;
(*node)->val = (*successor)->val;
removeNode(successor);
}
delete toDelete;
}
This C++ method employs double pointers to iterate and modify the tree structure. This allows for a more direct and less recursive approach to node deletion.