
Problem
Solution
Submissions
Delete a node in a BST given a key
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 12
Write a C# program to delete a node with a given key from a Binary Search Tree (BST). Return the root node reference of the BST after deleting the node with the given key. A Binary Search Tree is a binary tree where for each node, all elements in its left subtree are less than the node's value, and all elements in its right subtree are greater than the node's value.
Example 1
- Input: root = [5,3,6,2,4,null,7], key = 3
- Output: [5,4,6,2,null,null,7]
- Explanation:
- The tree before deletion:
5
/ \
3 6
/ \ \
247 - After deleting the node with key 3, the tree becomes:
5
/ \
4 6
/
2 \
7
- The tree before deletion:
Example 2
- Input: root = [5,3,6,2,4,null,7], key = 5
- Output: [6,3,7,2,4]
- Explanation:
- The tree before deletion:
5
/ \
3 6
/ \ \
2 4 7 - After deleting the node with key 5, the tree becomes:
6
/ \
3 7
/ \
2 4
- The tree before deletion:
Constraints
- The number of nodes in the tree is in the range [0, 10^4]
- -10^5 ≤ Node.val ≤ 10^5
- Each node has a unique value
- The key to be deleted exists in the BST
- Time Complexity: O(h) where h is the height of the tree. In the worst case, O(n) if the tree is skewed
- Space Complexity: O(h) for the recursion stack
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use the properties of a BST to locate the node to be deleted.
- Handle three cases: node with no children, node with one child, and node with two children.
- For a node with two children, find the successor (smallest value in the right subtree) or the predecessor (largest value in the left subtree).
- Replace the node's value with the successor's value and then delete the successor.
- Return the updated root of the tree.