Skip to main content

Delete Node in a BST

Medium
Data Structures and Algorithms
Editorial
Topics:
Binary Search Tree
Binary Tree
Tree

Given root, the root of a binary search tree, and key, remove the node whose value equals key and return the root of the resulting tree. A binary search tree is a binary tree where every value in a node's left subtree is smaller than the node's value, and every value in its right subtree is larger.

If the node to remove has no children, remove it directly. If it has one child, connect its parent to that child. If it has two children, replace its value with a suitable value from one subtree—such as the smallest value in its right subtree or the largest value in its left subtree—and then remove that replacement node.

All values are unique. The returned tree must be a valid binary search tree containing exactly the original values except key. If key does not occur in the tree, return the tree unchanged. The returned value is the new root; it may be null when the resulting tree is empty.

Example 1:

Input: root = [8,3,10,1,6,null,14,null,null,4,7,13], key = 3
Output: [8,4,10,1,6,null,14,null,null,null,7,13]
Explanation: The node 3 has two children. Replacing it with its in-order successor 4 and removing the original 4 preserves the search-tree ordering.

Example 2:

Input: root = [5,2,9,null,3,7,12], key = 12
Output: [5,2,9,null,3,7]
Explanation: The target is a leaf, so it can be removed without changing any other links.

Example 3:

Input: root = [6,4,11,2,5,8,13], key = 10
Output: [6,4,11,2,5,8,13]
Explanation: No node has value 10, so the original tree is returned unchanged.

Constraints:

  • 0 <= number of nodes in root <= 5000
  • -10^5 <= node values <= 10^5
  • -10^5 <= key <= 10^5
  • All node values in root are unique
  • root represents a valid binary search tree
  • The tree is encoded in level order, using null for missing children

Need help or want more practice?

Practise in an interviewGet AI Coach help