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
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)