SDE & MLE Prep

230. Kth Smallest Element in a BST

Problem

Return the k-th smallest value (1-indexed) in a binary search tree.

Example: [3,1,4,null,2], k = 1 → 1; [5,3,6,2,4,null,null,1], k = 3 → 3

Constraints: follow-up: the BST is modified often and k-th smallest is queried often.

In-order traversal of a BST is sorted; stop at the k-th visited node (iterative stack makes early exit easy).

Complexity: O(h + k).

class Solution:
    def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
        st, node = [], root
        while True:
            while node:
                st.append(node)
                node = node.left
            node = st.pop()
            k -= 1
            if k == 0:
                return node.val
            node = node.right