Kth smallest in a BST
Mediumtreebinary search treedfsstack
The tree is a valid BST. Return the kth value if all values were sorted ascending (k starts at 1).
Examples write a tree level by level, with null for a missing child: [3,9,20,null,null,15,7].
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
- 1 ≤ k ≤ number of nodes ≤ 10⁴
- 0 ≤ Node.val ≤ 10⁴
- Values are distinct
Submit checks your solution against 8 tests, including hidden ones.
// Provided by the judge: keep these definitions
class TreeNode {
constructor(val = 0, left = null, right = null) {
this.val = val
this.left = left
this.right = right
}
}
/**
* @param {TreeNode|null} root
* @param {int} k
* @return {int}
*/
function kthSmallest(root, k) {
}