Delete a Node in a Binary Search Tree

Problem Given the root of a binary search tree and a key, delete the node holding that key and return the root of the resulting tree, preserving the BST ordering property.

Input / Output

  • Input: root of a BST and an integer key.
  • Output: the root of the BST after deletion; the tree is returned unchanged if the key is absent.

Constraints

  • 0 <= number of nodes <= 10^4; node values are unique.
  • The key may not exist — that must be a silent no-op, not an error.
  • Deleting the root itself must work, which is why the function returns a root rather than mutating in place.

Example

  • root = [5,3,6,2,4,null,7], key = 3 → [5,4,6,2,null,null,7]: node 3 has two children, so its in-order successor 4 takes its place.
  • key = 5 (the root, two children) → either 6 or 4 becomes the new root depending on the successor-vs-predecessor choice; both are valid BSTs.
  • key = 10 → tree returned unchanged.
asked …
LeaderboardSalaryAccount