Kth Smallest in a BST
Find the k-th smallest value in a binary search tree.
The problem
Implement Solution.kthSmallest(root, k). root is the root TreeNode of a valid binary search tree: every value in a node's left subtree is smaller than the node's value, and every value in its right subtree is larger. Each node has val, left and right. Return the k-th smallest value in the tree, counting from 1, so k = 1 asks for the smallest value. Return an int. Trees are written in level order with None for a missing child. For [3, 1, 4, None, 2] the values in sorted order are 1, 2, 3, 4, so k = 3 returns 3. Constraints: the tree has 1 to 10,000 nodes with values from 0 to 10,000, and 1 <= k <= the number of nodes. Do not change the tree.
Starter code
class Solution:
def kthSmallest(self, root, k):
passPublic examples
root = [3, 1, 4, None, 2], k = 1gives1root = [2, 1, 3], k = 3gives3root = [0], k = 1gives0
Solving it in the practice book needs an active paid plan.
Open it in the practice book