Skip to main content
All Questions

Find the k-th smallest and k-th largest element in a binary search tree (BST).

Medium
Unlock detailed company stats for this questionUpgrade

Given the root of a binary search tree and an integer k, return the kth smallest value in the tree, counting from 1.

Trees in the examples and tests are written in level order, with null for a missing child.

Example 1

Input: root = [3, 1, 4, null, 2], k = 1 Output: 1 3 / \ 1 4 \ 2

Example 2

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

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

Constraints

  • The tree has n nodes, where 1 <= n <= 10^4.
  • 1 <= k <= n
  • 0 <= Node.val <= 10^4

Related courses

Course

Software Engineering Interview Prep

Land your dream software engineering role at Google, Amazon, Microsoft, Meta, Apple, and other top companies. Learn from mock interviews, frameworks, and advice from senior candidates—practice data structures, algorithms, system design, people management, behavioral interviews, and more.

Course

System Design Interviews

Learn how to answer the latest system design questions across product, infrastructure, and AI domains. Features in-depth video examples, written breakdowns, and helpful reference patterns. Watch senior engineers and managers answer these questions in mock interview videos.