Problem 423049 · medium · Level 04 Non-Linear Data Structures

k-th Lowest Bid in a Search Tree

BST · in-order traversal · iterative DFS · stack

Because of the BST ordering, an in-order traversal (left subtree, node, right subtree) visits the values in sorted order. That means the k-th node visited is the k-th smallest value, with no sorting required.

An auction house files every bid in a BST keyed by the amount, and no two bids are equal. Write kth_smallest(root, k) that returns the k-th lowest bid, counting from 1: k = 1 asks for the lowest bid in the tree.

Examples

    6
   / \
  2   8
   \
    4

Input:  root = [6, 2, 8, None, 4], k = 2
Output: 4
Explanation: In order, the bids are 2, 4, 6, 8.
        9
       / \
      5   12
     / \
    3   7
   /
  1

Input:  root = [9, 5, 12, 3, 7, None, None, 1], k = 4
Output: 7

Constraints

  • 1 <= k <= number of nodes <= 1000
  • All values are distinct.

Goals

  • Exploit the BST invariant: in-order traversal yields values in ascending order
  • Implement in-order traversal iteratively with an explicit stack
  • Stop a traversal early once the answer is known
Starting Python…