Kth Smallest Element in a BST
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,nullfor 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
- 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
Stuck?
See the solution run step by step on our example, then why it works and its complexity.
Next: more tree traversals problems
- 94Binary Tree Inorder TraversalEasysolve
- 144Binary Tree Preorder TraversalEasysolve
- 145Binary Tree Postorder TraversalEasysolve
- 530Minimum Absolute Difference in BSTEasysolve
- 98Validate Binary Search TreeMediumsolve
- 114Flatten Binary Tree to Linked ListMediumsolve
- 173Binary Search Tree IteratorMediumsolve
The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.