Delete Node in a BST

Given a root node reference of a Binary Search Tree (BST) and a key, the task is to delete the node with the given key in the BST and return the potentially updated root node reference of the BST. The deletion process involves two main stages: searching for the node to remove and deleting it if found.

Constraints

  • The number of nodes in the tree is in the range [0, 10000].
  • -100000 <= Node.val <= 100000
  • Each node has a unique value.
  • root is a valid binary search tree.
  • -100000 <= key <= 100000
Saving… · 11 lines
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right

class Solution:
def deleteNodeInBST(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:

Console

Click Run to execute sample tests.