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.
Basically, the deletion can be divided into two stages:
Example 1:
Input: root = [5,3,6,2,4,null,7], key = 3
Output: [5,4,6,2,null,null,7]
Example 2:
Input: root = [5,3,6,2,4,null,7], key = 0
Output: [5,3,6,2,4,null,7]
Example 3:
Input: root = [], key = 0
Output: []
Constraints:
[0, 10^4]
.-10^5 <= Node.val <= 10^5
root
is a valid binary search tree.-10^5 <= key <= 10^5
Could you solve it with time complexity O(height of tree)?
Given the 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.
The optimal approach is essentially a refined version of the naive approach, focusing on an efficient implementation, particularly for the case where the node to be deleted has two children.
null
.class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
if (root == null) {
return null;
}
if (key < root.val) {
root.left = deleteNode(root.left, key);
} else if (key > root.val) {
root.right = deleteNode(root.right, key);
} else {
// Node found, perform deletion
if (root.left == null) {
return root.right;
} else if (root.right == null) {
return root.left;
} else {
// Node has two children
TreeNode inorderSuccessor = findMin(root.right);
root.val = inorderSuccessor.val;
root.right = deleteNode(root.right, inorderSuccessor.val);
}
}
return root;
}
private TreeNode findMin(TreeNode node) {
while (node.left != null) {
node = node.left;
}
return node;
}
}