Skip to problem
←

Kth Smallest Element in a BST

Medium 0 attempts

Given the root of a binary search tree and an integer k, find the kth smallest value stored in the tree (using 1-based counting). Because of how a BST is ordered, visiting its nodes inorder naturally produces them from smallest to largest, which is worth keeping in mind here.

Function contract

root is a nonempty binary search tree with val, left, and right node properties; fixtures use level-order arrays. k is a valid one-based rank.

Output: Return the kth smallest node value, not the node or its index.

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

Explanation: The values in sorted order are [1,2,3,4,5,6]; rank 3 contains value 3.

Constraints
  • 1 <= k <= n <= 10^4
  • 0 <= Node.val <= 10^4
  • For every node, all left-subtree values are smaller and all right-subtree values are larger.

Iterative Inorder

Inorder traversal visits a BST in sorted order. Stop after visiting k nodes.

javascript
function kthSmallestElementInABst(root, k) {
  const stack = [];
  let current = root;
  while (current || stack.length) {
    while (current) {
      stack.push(current);
      current = current.left;
    }
    current = stack.pop();
    if (--k === 0) return current.val;
    current = current.right;
  }
}

Time: O(h + k) | Space: O(h) auxiliary space

Loading discussion…

Saved in this browser only. Private to you.

JavaScript