# CODE

```python
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
        stack = collections.deque()
        curr = root
        
        while stack or curr:
            # traverse all the way to the leftmost child
            while curr:
                stack.append(curr)
                curr = curr.left
            # process leftmost node
            curr = stack.pop()
            k -= 1
            if k == 0:
                return curr.val
            # visit right node of "V"
            curr = curr.right
```


---

# Agent Instructions: 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:

```
GET https://chiragjain.gitbook.io/neetcode/230-kth-smallest-element-in-a-bst/code.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
