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.
1public TreeNode 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) return root.right;
9 if (root.right == null) return root.left;
10 TreeNode minNode = getMin(root.right);
11 root.val = minNode.val;
12 root.right = deleteNode(root.right, minNode.val);
13 }
14 return root;
15}
16
17private TreeNode getMin(TreeNode node) {
18 while (node.left != null) node = node.left;
19 return node;
20}
The method deleteNode
in Java handles the deletion process by checking the existence of children and utilizing the inorder successor when needed.
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.