Kth Smallest Element in a BST
Examples
Example 1:
Input: root = [2,1,3], k = 1
Output: 1
Example 2:
Input: root = [4,3,5,2,null], k = 4
Output: 5
Example 1:
Input: root = [2,1,3], k = 1
Output: 1
Example 2:
Input: root = [4,3,5,2,null], k = 4
Output: 5
Given the root of a binary search tree, and an integer k, return the kth smallest value (1-indexed) in the tree.
A binary search tree satisfies the following constraints:
1 <= k <= The number of nodes in the tree <= 10000 <= Node.val <= 1000Perform an in-order traversal (left, node, right), which visits nodes in ascending order for a BST. Use an explicit stack to traverse iteratively and decrement k each time a node is visited. When k reaches zero, that node is the answer.
In-order traversal of a BST yields values in sorted order. Therefore, the k-th visited node is exactly the k-th smallest element. The iterative traversal preserves this order while using only stack space.
O(h + k)O(h)class Solution:
def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
stack = []
cur = root
while cur or stack:
while cur:
stack.append(cur)
cur = cur.left
cur = stack.pop()
k -= 1
if k == 0:
return cur.val
cur = cur.right
return 0