103. Delete a node in BST

Given the root node of a binary search tree (BST) and a value key. Return the root node of the BST after the deletion of the node with the given key value.

Note: As there can be many correct answers, the compiler returns true if the answer is correct, otherwise false.

Example 1:

Input : root = [5, 3, 6, 2, 4, null, 7] , key = 3

Output : [5, 4, 6, 2, null, null, 7]

Explanation :

Below is image of the original BST

Below is image where the node 3 is deleted

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 have node with value 0.

Now Your Turn!

Pick the correct output for the given input

Input : root = [5, 3, 6, 2, 4, null, 7] , key = 5

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= Number of nodes <= 104
  • -108 <= Node.val <= 108
  • All values in tree are unique.
  • -108 <= key <= 108

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
/**
* Definition for a binary tree node.
* struct TreeNode {
* int data;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int val) : data(val) , left(nullptr) , right(nullptr) {}
* };
**/
 
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
//your code goes here
}
};
Test Case

Input:

Root
Val