BST Node Deletion Problem
Given a binary search tree (BST) and a key value K
, your task is to delete the node with value K
. It is guaranteed that a node with value K
exists in the BST.
Explanation:
A binary search tree (BST) is a node-based binary tree data structure which has the following properties:
- The left subtree of a node contains only nodes with keys less than the node's key.
- The right subtree of a node contains only nodes with keys greater than the node's key.
Input:
The first line of input contains an integer 'T', denoting the number of test cases.
The first line of each test case contains the elements of the tree in level order, separated by a single space. A node with value -1 indicates a null node.
The second line of each test case is a single integer 'K', representing the node value to be deleted.
Output:
For each test case, return the root of the modified BST after the node with value 'K' is deleted.
Example:
For an input tree sequence: 20 10 35 5 15 30 42 -1 -1 -1 13 -1 -1 -1 -1 -1 -1
and K = 10
, the tree is:
Level 1 :
The root node = 20
Level 2 :
Left child of 20 = 10
Right child of 20 = 35
Level 3 :
Left child of 10 = 5
Right child of 10 = 15
Left child of 35 = 30
Right child of 35 = 42
Level 4 :
Left child of 5 = null (-1)
Right child of 5 = null (-1)
Left child of 15 = null (-1)
Right child of 15 = 13
Left child of 30 = null (-1)
Right child of 30 = null (-1)
Left child of 42 = null (-1)
Right child of 42 = null (-1)
Level 5 :
Left child of 13 = null (-1)
Right child of 13 = null (-1)
Constraints:
- 1 <= T <= 100
- 1 <= N <= 1000
- 1 <= data <= 10^9 and data ≠ -1
- 1 <= K <= 10^9
- Time limit: 1 second
Note:
You do not need to print any output. Implement the function to modify the BST and return the root of the updated tree.
Be the first one to answer
Add answer anonymously...
Top UBS C Developer interview questions & answers
Popular interview questions of C Developer
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app