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

# Kth Smallest Element in BST

## Problem

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

{% hint style="info" %}
For example:

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

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

{% endhint %}

## Solution

```
class Solution:
    def kthSmallest(self, root: TreeNode, k: int) -> int:
        self.s = None
        self.visited = 0
        self.helper(root, k)
        return self.s
        
    
    def helper(self, root,k):
        if root is None:
            return  
        self.helper(root.left,k)
        self.visited +=1
        if k == self.visited:
            self.s = root.val
            return
        self.helper(root.right, k)
        
#For any problems with inOrder traversal, in the 
#recursive method we have to traverse all the way 
#left before we do any operations

#We are using inOrder traversal approach

#We are keeping count of the nodes visited and 
#comparing this to our input k


#Time: O(h) where h is the height of the tree
#Space: O(h) because of call stack
```


---

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

```
GET https://joshualbarb.gitbook.io/leetcode-problems/binary-search-trees/kth-smallest-element-in-bst.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.
