Problem
You get the root root of a binary search tree (BST) and an integer k. In a BST, each node has at most two children: a left child and a right child.
The left subtree of a node is its left child and all the nodes below that child. The right subtree of a node is its right child and all the nodes below that child. In a BST, all values in the left subtree of a node are smaller than the node value. All values in the right subtree are larger.
Return the kth smallest value in the tree. Count from 1, so k = 1 gives the smallest value.
The examples show each tree as a list in level order. This list gives the nodes row by row, from left to right. The value null marks a missing child.
Example 1
- Input:
- root = [9,4,12,2,6], k = 3
- Output:
- 6
- Explanation:
- The values in sorted order are
2, 4, 6, 9, 12. The third value is6.
Example 2
- Input:
- root = [20,10,30,null,15], k = 1
- Output:
- 10
Example 3
- Input:
- root = [50,30,70,20,40,60,80], k = 7
- Output:
- 80
- Explanation:
- The tree has 7 nodes, so
k = 7gives the largest value.
Constraints
- n is the number of nodes in the tree.
- 1 <= k <= n <= 10^4
- 0 <= Node.val <= 10^4
Follow-up
Suppose that you often add and remove nodes, and you often need the kth smallest value. How can you make each query faster?
SysRound wrote this statement. A reference solution checks every example.
Related questions
Continue with questions that share topics or the same question type.
- Binary Search Tree to Greater Sum Tree
Coding · Binary Search Tree · Binary Tree · Depth-First Search
- Closest Binary Search Tree Value
Coding · Binary Search · Binary Search Tree · Binary Tree
- Closest Binary Search Tree Value II
Coding · Binary Search Tree · Binary Tree · Depth-First Search
- Validate Binary Search Tree
Coding · Binary Search Tree · Binary Tree · Depth-First Search
Sources · 2 references
These records explain where the question appears. A company tag or candidate report does not guarantee a future interview question.
Hello Interview · 3 records
Amazon
Leetcode 230. Kth Smallest Element in a BST
Reported Jan 12, 2025 · 1 source report
SENIOR
Source snapshot: Nov 12, 2026
View sourceGoogle
Leetcode 230. Kth Smallest Element in a BST
Reported Feb 7, 2025 · 1 source report
JUNIOR
Source snapshot: Nov 12, 2026
View sourceMeta
Leetcode 230. Kth Smallest Element in a BST
Reported Mar 3, 2025 · 1 source report
SENIOR
Source snapshot: Nov 12, 2026
View source
LeetCode company tags · 1 record
Uber
Kth Smallest Element in a BST
Reported date not specified · Source window: 6mo