LeetCode 450: Delete Node in a BST Solution
Master LeetCode problem 450 (Delete Node in a BST), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
450. Delete Node in a BST
Problem Explanation
Explanation
To delete a node in a binary search tree (BST), we need to find the node with the given key and perform the deletion. There are three cases to consider:
- If the node to be deleted has no children, we simply remove the node.
- If the node to be deleted has one child, we replace the node with its child.
- If the node to be deleted has two children, we find the inorder successor (smallest node in the right subtree), copy its value to the node to be deleted, and then recursively delete the inorder successor.
Time complexity: O(h), where h is the height of the tree. Space complexity: O(h) for the recursive call stack.
Solution Code
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 {
if (root.left == null) {
return root.right;
} else if (root.right == null) {
return root.left;
}
TreeNode minNode = findMin(root.right);
root.val = minNode.val;
root.right = deleteNode(root.right, root.val);
}
return root;
}
private TreeNode findMin(TreeNode node) {
while (node.left != null) {
node = node.left;
}
return node;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 450 (Delete Node in a BST)?
This page provides optimized solutions for LeetCode problem 450 (Delete Node in a BST) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 450 (Delete Node in a BST)?
The time complexity for LeetCode 450 (Delete Node in a BST) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 450 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 450 in Java, C++, or Python.