Open songyy5517 opened 5 months ago
Approach: Discuss by case
head
to the parent node, and a boolean variable left
to record whether the current node is a left child;Otherwise, delete the target node from the tree: (1)If the target node has a right subtree, then
(2)Otherwise, we move the left subtree of the target node as the child of the parent node of the target node;
Complexity Analysis
class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
// Intuition: Locate & Delete. First, we need to locate the given node.
// If exists, then delete it. The key here is how to realize the delete operation.
// 1. Exception handling
if (root == null)
return null;
// 2. Locate the given node
TreeNode target = root, head = new TreeNode(Integer.MIN_VALUE);
head.right = target;
Boolean left = false; // indicates whether it is the left son of its father node
while (target != null && target.val != key){
head = target;
if (target.val > key){
target = target.left;
left = true;
}
else{
target = target.right;
left = false;
}
}
if (target == null)
return root;
// 3. Delete the target node
// If the target node has the right substree
if (target.right != null){
TreeNode t_left = target.left, t_right = target.right;
TreeNode last_node = t_right;
// Get the minimal node in the right subtree
while (last_node.left != null)
last_node = last_node.left;
if (left)
head.left = t_right;
else
head.right = t_right;
last_node.left = t_left;
}
else {
if (left)
head.left = target.left;
else
head.right = target.left;
}
return head.val == Integer.MIN_VALUE ? head.right : root;
}
}
2024/6/12
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:
Example 2:
Example 3:
Intuition The problem can be basically split into two subtasks. The first is to locate the given node. The second one is to delete it from the whole tree. Therefore, we can first search for the target node in the whole tree. If not exists, return the root node; otherwise, we delete it from the tree. To implement the delete operation, we need to keep a pointer to the parent node of the target node. Then we perform different delete operation according to whether the target node has a right substree.