Menu
CoddyTech

Kth Smallest Element in a BST

You get a binary search tree as the array root in heap order: the root is at index 0, the children of index i are at 2*i+1 (left) and 2*i+2 (right), and -1 marks an empty spot. The array may end with extra -1 entries. At every node, the left subtree holds only smaller values and the right subtree only larger ones.

Return the k-th smallest value in the tree, counting from 1.

Function

kthSmallest(root: integer-array, k: integer) → integer
rootinteger-array
the binary search tree in level order, with -1 for an empty spot
kinteger
the position to find in increasing order, starting at 1
Returnsinteger
the k-th smallest value in the tree

Constraints

  • 1 ≤ root.length ≤ 32767
  • Each root[i] is -1 or a value with 0 ≤ root[i] ≤ 105.
  • root[0] is never -1, so the tree has at least one node.
  • The array may end with extra -1 entries past the last node.
  • Both children of an empty spot are empty too, and the depth is at most 14.
  • The ordering rule holds at every node, so no value appears twice.
  • 1 ≤ k ≤ the number of nodes in the tree.

Examples

Input
root = [41, 17, 65, 6, 29, -1, 90, -1, -1, 22]k = 4
Output
29
Explanation
In increasing order the values are 6, 17, 22, 29, 41, 65, 90, and the fourth is 29. It is the largest of the four values in the root's left subtree.
challenge icon

Follow-up

If the tree changes often and you are asked for the k-th smallest value many times, what could each node store so that every query takes O(h)?

Reset code
def kthSmallest(root, k):
    # Write code here

Test #1

Test #2

Arguments

root = [41, 17, 65, 6, 29, -1, 90, -1, -1, 22]
k = 4

Expected Output

29