Leetcode•May 30, 2025
Kth Smallest Element in a BST
Hazrat Ali
Leetcode
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
Solution
/**
* @param {TreeNode} root
* @param {number} k
* @return {number}
*/
const kthSmallest = (root, k) => {
const inorder = node => {
if (node) {
inorder(node.left);
if (++count === k) {
result = node.val;
return;
}
inorder(node.right);
}
};
let count = 0;
let result = 0;
inorder(root);
return result;
};