Blind 75
32 / 75Free practice

Kth Smallest Element in a BST

Medium · Trees

Jump to code

Given a BST with distinct values and a valid one-based rank k, return its kth smallest value.

Examples

Example 1

root = [3,1,4,null,2]
k = 1

Output: 1

Example 2

root = [5,3,6,2,4,null,null,1]
k = 3

Output: 3

Constraints

  • 1 <= k <= The number of nodes in the tree <= 1000
  • 0 <= Node.val <= 1000

Function contract

Trees use level-order arrays, with null for a missing child. Your code receives TreeNode objects with val, left, and right fields.

Need a hint?

In-order traversal of a BST produces sorted values.

Asked in real interviews

Candidates reported versions of Kth Smallest Element in a BST from these company interviews. Some company questions are locked and open with Premium or XP.

Browse all real coding interview questions

Accepted submissions mark this problem complete. Progress stays in this browser.

Run checks 5 examples. Submit checks all 7 cases. A free account runs this problem; no XP needed.
Language
Case 1
Input
[
  [
    3,
    1,
    4,
    null,
    2
  ],
  1
]
Expected
1
Case 2
Input
[
  [
    5,
    3,
    6,
    2,
    4,
    null,
    null,
    1
  ],
  3
]
Expected
3
Case 3
Input
[
  [
    1
  ],
  1
]
Expected
1
Case 4
Input
[
  [
    2,
    1,
    3
  ],
  3
]
Expected
3
Case 5
Input
[
  [
    4,
    2,
    6,
    1,
    3,
    5,
    7
  ],
  4
]
Expected
4

Drafts are saved per language in this browser when storage is available.