Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Delete Node In BST

Medium Acceptance 65.20% Points 30.00

You are given the root of a Binary Search Tree (BST) and an integer key. Your task is to delete the node with the given key from the BST while maintaining the BST properties and return the root of the updated tree.

When deleting a node:

  • If the node has no children, simply remove it.
  • If the node has one child, replace it with its child.
  • If the node has two children, replace it with its inorder successor (or predecessor) and maintain the BST structure.

If the key does not exist, return the original tree unchanged.

Examples
Example 1

image Input: root = [5,3,6,2,4,null,7], key = 3
Output: [5,4,6,2,null,null,7]
Explanation: The node with value 3 is deleted while maintaining the BST property.

Example 2

image Input: root = [5,3,6,2,4,null,7], key = 0
Output: [5,3,6,2,4,null,7]
Explanation: The key does not exist, so the BST remains unchanged.

Example 3

image Input: root = [1], key = 1
Output: []
Explanation: The only node is deleted, resulting in an empty BST.

Constraints
    • 0 = Number of nodes = 105
    • -10? = Node.data, key = 10?
Companies
Samsung PhonePe
Topics
Tree Traversal Binary Tree
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions