> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Kth Smallest Element in a BST Python Solution

> Tested Python solution for LeetCode 230 with 12 pytest cases. Generate a practice environment with lcpy.

LeetCode 230, Medium. Topics: Tree, Depth-First Search, Binary Search Tree, Binary Tree. [View on LeetCode](https://leetcode.com/problems/kth-smallest-element-in-a-bst/description/).

Generate this problem as a practice environment: tested reference solution, 12 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 230   # by problem number
lcpy gen -s kth_smallest_element_in_a_bst   # by problem name
```

## Problem

Given the `root` of a binary search tree, and an integer `k`, return the `k`th smallest value (1-indexed) of all the values of the nodes in the tree.

### Examples

![Example 1](https://assets.leetcode.com/uploads/2021/01/28/kthtree1.jpg)

```
Input: root = [3,1,4,null,2], k = 1
Output: 1
```

![Example 2](https://assets.leetcode.com/uploads/2021/01/28/kthtree2.jpg)

```
Input: root = [5,3,6,2,4,null,null,1], k = 3
Output: 3
```

### Constraints

* The number of nodes in the tree is `n`.
* `1 <= k <= n <= 10^4`
* `0 <= Node.val <= 10^4`

**Follow up:** If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/kth_smallest_element_in_a_bst/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/kth_smallest_element_in_a_bst/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from leetcode_py import TreeNode


class Solution:
    # Inorder Recursive
    # Time: O(k)
    # Space: O(h)
    def kth_smallest(self, root: TreeNode[int] | None, k: int) -> int:
        def inorder(node: TreeNode[int] | None):
            if not node:
                return
            yield from inorder(node.left)
            yield node.val
            yield from inorder(node.right)

        for i, val in enumerate(inorder(root)):
            if i == k - 1:
                return val

        raise ValueError(f"Tree has fewer than {k} nodes")


# Binary Tree Traversal Patterns
#
# def inorder(node):
#     if node:
#         inorder(node.left)
#         print(node.val)
#         inorder(node.right)
#
# def preorder(node):
#     if node:
#         print(node.val)
#         preorder(node.left)
#         preorder(node.right)
#
# def postorder(node):
#     if node:
#         postorder(node.left)
#         postorder(node.right)
#         print(node.val)
```

## Complexity

| Time | Space |
| ---- | ----- |
| O(k) | O(h)  |

## Tags

[Grind 75](/catalog/grind-75), [Grind](/catalog/grind), [Blind 75](/catalog/blind-75), [NeetCode 150](/catalog/neetcode-150), [NeetCode 250](/catalog/neetcode-250), [NeetCode All](/catalog/neetcode), [AlgoMaster 75](/catalog/algo-master-75).
