#450

Delete Node in a BST

specialist · 800 · lc medium +31 · verified · 54.3% accepted · 10,366 likes · top 47%

play →

Description

Given the root of a binary search tree and an integer key, delete the node whose value is key from the BST while preserving the BST ordering property. Return the root of the updated tree, which may have changed.

Example 1:

Input: root = [5,3,6,2,4,null,7], key = 3
Output: [5,4,6,2,null,null,7]
Explanation: Given key to delete is 3. So we find the node with value 3 and delete it.
One valid answer is [5,4,6,2,null,null,7], shown in the above BST.
Please notice that another valid answer is [5,2,6,null,4,null,7] and it's also accepted.

Example 2:

Input: root = [5,3,6,2,4,null,7], key = 0
Output: [5,3,6,2,4,null,7]
Explanation: The tree does not contain a node with value = 0.

Example 3:

Input: root = [], key = 0
Output: []

Code

1
2
3
4
5
6
7
8
9