Kth Smallest Element in a BST

Medium#230in-order

You get the root of a binary search tree and a number k. Return the k-th smallest value in the tree, counting from 1. Our tree: 13 with children 7 and 18; 7 has children 3 and 10; 10 has a left child, 8; 18 has a right child, 25. k = 4 — the answer is 10.

input
root: a binary search tree, written as on LeetCode: its values level by level, left to right, null for a missing child. Every value in a node's left subtree is smaller than the node's, every value in its right subtree larger. k: a number from 1 to the number of nodes.
returns
The k-th smallest value in the tree, counting from 1.
constraints
  • 1 ≤ n, the number of nodes, ≤ 3000
  • 1 ≤ k ≤ n
  • 0 ≤ Node.val ≤ 10⁴
  • root is a binary search tree
our 12 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @param {number} k
 * @return {number}
 */
function kthSmallest(root, k) {

}
Ctrl ↵
format
reset

saved in this browser

12 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more tree traversals problems

Pattern “Tree traversals” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.