KatInterview

Find the K-th Smallest Element in a BST

Trees & GraphsAuto-graded · 18 test cases
MediumAuto-gradedTrees & Graphstrees-graphstreesin-order-traversal

Last updated

Find the k-th smallest key in a binary search tree represented as a level-order array.

Given the level-order array representation of a Binary Search Tree (BST) and an integer k, return the key of the $k$-th smallest node in the tree (1-indexed).

A valid Binary Search Tree satisfies the standard ordering property: for any given node, all elements in its left subtree are strictly smaller than its key, and all elements in its right subtree are strictly larger than its key.

The input tree root is formatted as a level-order array of values where None indicates missing/null nodes (similar to standard binary tree array representations):

  • root[0] corresponds to the root node.
  • Subsequent non-null nodes in broad level-order assign the next elements of the list to their left and right children.

Constraints

  • $1 \le N \le 10^4$, where $N$ is the number of nodes in the BST.
  • $1 \le k \le N$.
  • Tree node keys are distinct integers in the range $[-10^9, 10^9]$.
  • root represents a valid BST.

Examples

Example 1

Input: kth_smallest_in_bst([5, 3, 6, 2, 4, None, None, 1], 3)

Output: 3

Example 2

Input: kth_smallest_in_bst([3, 1, 4, None, 2], 1)

Output: 1

Example 3

Input: kth_smallest_in_bst([5, 3, 6, 2, 4, None, None, 1], 6)

Output: 6

Hints

Hint 1

Recall that an in-order traversal (left child, root node, right child) of a Binary Search Tree visits elements in strictly ascending order.

Hint 2

You do not need to construct the full sorted sequence of all $N$ elements; you can terminate your traversal early as soon as you visit the $k$-th node.

Hint 3

Using an explicit stack allows you to perform an iterative in-order traversal efficiently without relying on deep recursion.