DEV Community

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

Posted on

Day 14 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/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
Enter fullscreen mode Exit fullscreen mode

Top comments (0)