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/find-k-th-smallest-element-in-bst/1
k-th Smallest in BST
Difficulty: Medium Accuracy: 43.53%
Given the root of a BST and an integer k, the task is to find the kth smallest element in the BST. If there is no kth smallest element present then return -1.
Examples:
Input: root = [20, 8, 22, 4, 12, N, N, N, N, 10, 14], k = 3
Output: 10
Explanation: 10 is the 3rd smallest element in the BST.
Input: root = [2, 1, 3], k = 5
Output: -1
Explanation: There is no 5th smallest element in the BST as the size of BST is 3.
Constraints:
1 β€ number of nodes, k β€ 104
1 β€ node->data β€ 104
Solution:
class Solution:
def kthSmallest(self, root, k):
self.count = 0
self.res = -1
def inorder(node):
if not node or self.res != -1:
return
inorder(node.left)
self.count += 1
if self.count == k:
self.res = node.data
return
inorder(node.right)
inorder(root)
return self.res
Top comments (0)