DEV Community

Cover image for Day 15 of 100 days dsa coding challenge
Manasi Patil
Manasi Patil

Posted on

Day 15 of 100 days dsa coding challenge

Taking on a new challenge: solving GeeksforGeeks POTD daily and sharing my solutions! πŸ’»πŸ”₯
The goal: sharpen problem-solving skills, level up coding, and learn something new every day. Follow my journey! πŸš€

100DaysOfCode #CodingChallenge #ProblemSolving #GeeksforGeeks #DeveloperJourney

Problem:

https://www.geeksforgeeks.org/problems/remove-bst-keys-outside-given-range/1

Remove BST keys outside given range

Difficulty: Medium Accuracy: 59.92%

Given the root of a Binary Search Tree (BST) and two integers l and r, remove all the nodes whose values lie outside the range [l, r].
Note: The modified tree should also be BST.

Examples:
Input: root = [6, -13, 14, N, -8, 13, 15, N, N, 7], l = -10, r = 13

Output: [6, -8, 13, N, N, 7]


Explanation: All the nodes outside the range [-10, 13] are removed and the modified tree is a valid BST.

Input: root = [14, 4, 16, 2, 8, 15, N, -8, 3, 7, 10], l = 2, r = 6


Output: [4, 2, N, N, 3]


Explanation: All the nodes outside the range [2, 6] are removed and the modified tree is a valid BST.

Constraints:
1 ≀ number of nodes ≀ 104
1 ≀ node->data ≀ 104
1 ≀ l ≀ r ≀ 104

Solution:
class Solution:
def removekeys(self, root, l, r):
if not root:
return None
root.left = self.removekeys(root.left, l, r)
root.right = self.removekeys(root.right, l, r)
if root.data < l:
return root.right
if root.data > r:
return root.left
return root

Top comments (0)