> For the complete documentation index, see [llms.txt](https://maksimdan.gitbook.io/interview-practice-problems/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://maksimdan.gitbook.io/interview-practice-problems/leetcode_sessions/230-kth-smallest-element-in-a-bst.md).

# 230 Kth Smallest Element in a BST

Given a binary search tree, write a function`kthSmallest`to find the**k**th smallest element in it.

**Note:**\
You may assume k is always valid, 1 ? k ? BST's total elements.

**Follow up:**\
What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?

**The Idea:** Just do inorder traversal until the kth element is reached. Admitted, this is terrible python code (with the use of references), but it surprising scored in the top percentile range.

**Complexity:** O(N) time O(N) space

```python
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def kthSmallest(self, root, k):
        """
        :type root: TreeNode
        :type k: int
        :rtype: int
        """
        count = [k]
        stop = [False]
        val = [0]
        self.in_order_to_k(root, count, stop, val)
        return val[0]


    def in_order_to_k(self, root, cnt, stop, val):
        """
        :type root: TreeNode
        :type cnt: int
        :rtype: void
        """
        if (root and not stop[0]):
            self.in_order_to_k(root.left, cnt, stop, val)
            cnt[0] -= 1
            if (cnt[0] == 0 and not stop[0] and root):
                val[0] = root.val
                stop[0] = True
            self.in_order_to_k(root.right, cnt, stop, val)
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://maksimdan.gitbook.io/interview-practice-problems/leetcode_sessions/230-kth-smallest-element-in-a-bst.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
