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) 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) return root->right;
9 if (!root->right) 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
17TreeNode* getMin(TreeNode* node) {
18 while (node->left) node = node->left;
19 return node;
20}
This code deletes a node from a BST, handling different cases depending on the existence of children. When the node has two children, it is replaced by 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.
1
This iterative Python solution uses a dummy node to help bypass complications from root node deletion and ensures an effective, non-recursive approach.