</>CodexBash
Back to problems
Not started

The kth smallest value in a search tree

Medium
2000 ms limit256 MB memoryBinary searchTrees

Stuck?

Show a hint

An inorder walk of a search tree produces sorted values. Walk inorder and count to k, and stop as soon as you get there.

Next in this lesson

Find it by halving

Given a binary search tree and a number k, report the kth smallest value in it. k = 1 means the smallest.

Worked example#

      5
     / \
    3   6
   / \
  2   4
 /
1

Read in order, the values are 1 2 3 4 5 6. So k = 3 gives 3.

The idea#

The whole problem is one observation: an inorder walk of a search tree visits its values in increasing order.

That falls out of the tree's own rule. At any node, everything on the left is smaller and everything on the right is larger, so "left subtree, then me, then right subtree" is exactly sorted order.

So walk inorder and count. When the count reaches k, that is the answer.

walk(node):
    walk(node.left)
    count += 1
    if count == k: answer = node.val
    walk(node.right)

Stopping early#

Collecting every value into a list and taking index k - 1 works and is a fine first version. But you can stop the moment you have counted k, and for a small k on a large tree that is the difference between touching every node and touching about k of them plus the path down to them.

Stopping needs a little care: once the answer is found, the recursion must not keep walking right subtrees on the way back up. A check at the top of the function is enough.

Why this is the BST lesson worth learning#

Almost every "kth", "range", "closest value" or "sorted order" question about a search tree is this walk with the counting changed. Once inorder-is-sorted is in your hands, those stop being separate problems.

Constraints#

  • 1 <= k <= number of nodes <= 100000
  • The tree really is a search tree, and values are distinct

About the input#

The tree is written level by level with null for a missing child, the count first, then k.

Input

root is a count then that many tokens level by level. Then k on its own line.

Output

Print the kth smallest value.

Examples

Input

8
5 3 6 2 4 null null 1
3

Output

3

In order the values are 1 2 3 4 5 6, so the third is 3.

Input

3
2 1 3
1

Output

1

The smallest is the leftmost node.

Input

3
2 1 3
3

Output

3

The largest, which is the rightmost node.

Something wrong with this problem? Report an issue

Ready to try it

Write your solution in C, C++, Java or Python and see every test case come back with the time and memory it took.

Free, and it stays free. No card.