450. Delete Node in a BST
Asked at 11Amazon37Bloomberg34Google31Meta20Microsoft20Uber55Oracle52ByteDance50Flipkart43Infosys39LinkedIn32
Problem
Delete the node with value key from a BST, if it exists, and return the root of a valid BST. Any valid result is accepted.
Example: [5,3,6,2,4,null,7], key = 3 → [5,4,6,2,null,null,7]
Constraints: follow-up: O(height) time.
Find the node. 0 or 1 child → replace it with that child. 2 children → copy the in-order successor (min of the right subtree) into it, then delete the successor from the right subtree.
Complexity: O(h).
class Solution:
def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:
if not root:
return None
if key < root.val:
root.left = self.deleteNode(root.left, key)
elif key > root.val:
root.right = self.deleteNode(root.right, key)
else:
if not root.left or not root.right:
return root.left or root.right
succ = root.right
while succ.left:
succ = succ.left
root.val = succ.val
root.right = self.deleteNode(root.right, succ.val)
return root
assert tree_vals(Solution().deleteNode(make_tree([5, 3, 6, 2, 4, None, 7]), 3)) == [5, 4, 6, 2, None, None, 7]
assert tree_vals(Solution().deleteNode(make_tree([5, 3, 6, 2, 4, None, 7]), 0)) == [5, 3, 6, 2, 4, None, 7]
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;
if (root.right == null) return root.left;
TreeNode succ = root.right;
while (succ.left != null) succ = succ.left;
root.val = succ.val;
root.right = deleteNode(root.right, succ.val);
}
return root;
}
}
func deleteNode(root *TreeNode, key int) *TreeNode {
if root == nil {
return nil
}
switch {
case key < root.Val:
root.Left = deleteNode(root.Left, key)
case key > root.Val:
root.Right = deleteNode(root.Right, key)
default:
if root.Left == nil {
return root.Right
}
if root.Right == nil {
return root.Left
}
succ := root.Right // two children: take the in-order successor's value
for succ.Left != nil {
succ = succ.Left
}
root.Val = succ.Val
root.Right = deleteNode(root.Right, succ.Val)
}
return root
}