Delete a node in BST

Binary Search Trees Medium Medium
  • Fun Fact: This problem is very fundamental in the field of database management systems (DBMS)
  • When you delete a record from the database, if it's organized in a binary search tree manner, the DBMS under the hood performs exactly this operation of finding and deleting a node from a BST
  • So think about it, every time you hit 'delete' on an item in a software application, you're indirectly making use of this BST deletion logic

Given the root node of a binary search tree (BST) and a value key.

Return the root node of the BST after the deletion of the node with the given key value.

Examples:

Input : root = [5, 3, 6, 2, 4, null, 7] , key = 3

Output : [5, 4, 6, 2, null, null, 7]

Explanation : Below is image of the original BST



Below is image where the node 3 is deleted


Input : root = [5, 3, 6, 2, 4, null, 7] , key = 0

Output : [5, 3, 6, 2, 4, null, 7]

Explanation : The tree does not have node with value 0.

Input : root = [5, 3, 6, 2, 4, null, 7] , key = 5

Constraints

  • 1 <= Number of nodes <= 104
  • -108 <= Node.val <= 108
  • All values in tree are unique.
  • -108 <= key <= 108

Hints

  • Search for the key in the BST. Once found, If it has no children, remove it (return None). If it has one child, replace it with its child. If it has two children, replace it with the smallest node in the right subtree (inorder successor) or the largest node in the left subtree (inorder predecessor).
  • "Use an iterative approach to locate the node. Use the same deletion logic as the recursive method but with a loop."

Company Tags

Twilio AMD NVIDIA eBay Riot Games Byju's Unity Technologies IBM Lyft Cerner Target Instacart Robinhood Morgan Stanley Medtronic Walmart Siemens Healthineers Teladoc Health Chewy Zynga JPMorgan Chase Johnson & Johnson Swiggy Nutanix Electronic Arts Google Microsoft Amazon Meta Apple Netflix Adobe