Delete Node in a BST

Medium · Trees · Tree · Binary Search Tree · Binary Tree

Problem

Given the root of a binary search tree and an integer key, delete the node whose value is key (if there is one) and return the root of the resulting tree.

The result must still be a valid binary search tree holding every other value. When the deleted node has two children several trees are valid, and any of them is accepted; the tests check that the tree is a BST with exactly the right values.

Try to do it in O(height) time.

Examples

Input: root = [8,4,12,2,6,None,14], key = 12
Output: [8,4,14,2,6]

12 has only a right child, so 14 takes its place.

Input: root = [8,4,12,2,6,None,14], key = 4
Output: [8,6,12,2,None,None,14]

4 has two children; its in-order successor 6 takes its place. Putting its predecessor 2 there instead would also be accepted.

Input: root = [8,4,12], key = 5
Output: [8,4,12]

5 is not in the tree, so nothing changes.

Constraints

Approaches

Follow-up

Using the in-order predecessor (the rightmost node of the left subtree) is just as valid and gives a different tree, which is why any valid answer is accepted. Repeated deletions in this way can unbalance the tree; self-balancing trees (AVL, red-black) delete the same way and then rotate. The use cases below find the successor on its own, and delete a whole range of values at once.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…