Design Gurus Logo
Delete Node in a BST (medium)

Problem Statement

Given a root node of the binary search tree, and an integer value key, return the root of the updated BST after deleting the node having a value equal to key.

If BST doesn't contain the node having value equal to key, return the same binary tree.

Examples

Example 1:

  • Input: [8, 3, 10, 1, 6, null, 14, null, null, 4, 7, 13], key = 3
Image
  • Expected Output: [8, 4, 10, 1, 6, null, 14, null, null, null, 7, 13]
  • Justification: After removing the node with value 3, its right subtree's smallest value (4) replaces it to maintain the BST structure.

Example 2:

  • Input: [20, 10, 30, null, 15, 25, 35], key = 10
Image
  • Expected Output: [20, 15, 30, null, null, 25, 35]
  • Justification: The node 10 is removed and replaced by its right child 15 to keep the tree's integrity.

Example 3:

  • Input: [50, 30, 70, 20, 40, 60, 80], key = 10
Image
  • Expected Output: [50, 30, 70, 20, 40, 60, 80]
  • Justification: The BST doesn't contain the node with value 10. So, it returns the original BST.

Try it yourself

Try solving this question here:

Python3
Python3

. . . .

.....

.....

.....

Unlock this and all other premium problems.
No code editor for this lesson
This lesson focuses on concepts and theory