Kth Smallest Element in a BST

MediumTrees
Next
TreeBSTDFS

Given a valid binary search tree and an integer k, find the k-th smallest value (counting from 1) stored in it. Build the tree from the level-order input yourself, then solve the problem.

Input

Line 1: the tree in level order with null for missing children. Line 2: k.

Output

Print the k-th smallest value.

Constraints

1 <= k <= number of nodes <= 2000 The tree is a valid BST with distinct values.

Example 1
Input
3 1 4 null 2
1
Output
1

The smallest value in the tree is 1.

Example 2
Input
5 3 6 2 4 null null 1
3
Output
3

Inorder is 1 2 3 4 5 6, so the 3rd is 3.

Hints

Kth Smallest Element in a BST - Medium Trees Problem | Skill Shiksha