KatInterview

Retrieve Kth Smallest Element from Array-Encoded BST

Trees & GraphsAuto-graded · 19 test cases
MediumAuto-gradedTrees & Graphsbinary-search-treein-order-traversaliterative

Last updated

Tests in-order traversal of a binary search tree encoded in parallel arrays, with early termination and iterative stack management.

Problem

You are given a binary search tree where all node values are distinct integers. Your task is to find the kth smallest element in this tree, where k uses one-based indexing.

The tree structure is encoded using parallel arrays:

  • values[i] holds the integer value stored at node i
  • left[i] contains the index of node i's left child, or -1 if none exists
  • right[i] contains the index of node i's right child, or -1 if none exists
  • root is the index of the root node, or -1 if the tree is empty

All arrays have the same length n, which equals the total number of nodes.

Return the kth smallest value in the tree. If the tree is empty or k falls outside the valid range [1, n], return -1 as a sentinel value.

Note that -1 may also appear as a legitimate node value. The caller distinguishes error cases from valid results by checking whether k was in range.

Constraints

  • 0 ≤ n ≤ 200,000, where n = len(values) = len(left) = len(right)
  • Each child index is either a valid node index or -1
  • The arrays encode a single acyclic tree structure reachable from root
  • All values are distinct integers (may include negative numbers)
  • The tree satisfies the binary search tree property: for every node, all values in its left subtree are smaller and all values in its right subtree are larger
  • k is an integer and may be outside the valid range
  • The tree may be highly unbalanced (a single chain of depth n)

Examples

Example 1

Input: find_kth_smallest_bst([3, 1, 4, 2], [1, -1, -1, -1], [2, 3, -1, -1], 0, 1)

Output: 1

Example 2

Input: find_kth_smallest_bst([3, 1, 4, 2], [1, -1, -1, -1], [2, 3, -1, -1], 0, 3)

Output: 3

Example 3

Input: find_kth_smallest_bst([], [], [], -1, 1)

Output: -1

Hints

Hint 1

In-order traversal of a BST visits nodes in ascending order by value

Hint 2

You can stop traversing as soon as you've visited k nodes—no need to see the entire tree

Hint 3

Use an explicit stack to avoid recursion depth issues with deep trees