Skills101
← All coding problems

Kth Smallest Element in a BST

mediumTrees+20 XPTime limit 2s

Find the k-th smallest value (1-based) in a binary search tree.

Tree format. A binary tree is given on one line in level order (top to bottom, left to right), with null for a missing child — the same way most interview platforms show trees. Trailing nulls are left out, and an empty tree is the single word null. Example: 3 9 20 null null 15 7 is

    3
   / \
  9   20
     /  \
    15   7

Input:

  • line 1: the BST
  • line 2: k

Output: the k-th smallest value.

Constraints: 1 ≤ k ≤ nodes ≤ 10⁴, values are distinct. The tree has at most 10⁴ nodes and its height is at most 500, so recursion is safe in every language.

Think about it: the inorder traversal of a BST visits values in sorted order — stop after k nodes. With an iterative stack you never visit more than height + k nodes.

Sample input 1

3 1 4 null 2
1

Sample output 1

1

Sample input 2

5 3 6 2 4 null null 1
3

Sample output 2

3

📖 Stuck? Learn the pattern

Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).

Loading editor…

Log in to run and submit your code — it's free.