Kth Smallest Element in a BST LeetCode Solution

Problem – Kth Smallest Element in a BST

Given the root of a binary search tree, and an integer k, return the kth smallest value (1-indexed) of all the values of the nodes in the tree.

Example 1:

Input: root = [3,1,4,null,2], k = 1
Output: 1

Example 2:

Input: root = [5,3,6,2,4,null,null,1], k = 3
Output: 3

Constraints:

  • The number of nodes in the tree is n.
  • 1 <= k <= n <= 104
  • 0 <= Node.val <= 104

Follow up: If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?

Kth Smallest Element in a BST LeetCode Solution in Java

def findNode(node, res):
            if len(res) > 1:
                return

            if node.left:
                findNode(node.left, res)

            res[0] -= 1
            if res[0] == 0:
                res.append(node.val)
                return
            
            if node.right:
                findNode(node.right, res)
                
        res = [k]
        findNode(root, res)
        return res[1]

Kth Smallest Element in a BST LeetCode Solution in Python

def kthSmallest(self, root, k):
    self.k = k
    self.res = None
    self.helper(root)
    return self.res

def helper(self, node):
    if not node:
        return
    self.helper(node.left)
    self.k -= 1
    if self.k == 0:
        self.res = node.val
        return
    self.helper(node.right)

Kth Smallest Element in a BST LeetCode Solution in c++

int kthSmallest(TreeNode* root, int k) {
    return find(root, k);
}
int find(TreeNode* root, int& k) {
    if (root) {
        int x = find(root->left, k);
        return !k ? x : !--k ? root->val : find(root->right, k);
    }
}
Kth Smallest Element in a BST LeetCode Solution Review:

In our experience, we suggest you solve this Kth Smallest Element in a BST LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the Kth Smallest Element in a BST LeetCode Solution

Find on LeetCode

Conclusion:

I hope this Kth Smallest Element in a BST LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

LeetCode Solutions

Hacker Rank Solutions

CodeChef Solutions

Leave a Reply

Your email address will not be published. Required fields are marked *