> For the complete documentation index, see [llms.txt](https://mayanktyagi3111.gitbook.io/interview-prep/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://mayanktyagi3111.gitbook.io/interview-prep/trees/sum-of-k-smallest-elements-in-bst.md).

# Sum of k smallest elements in BST

Given[ Binary Search Tree](http://quiz.geeksforgeeks.org/binary-search-tree-set-1-search-and-insertion/). The task is to find sum of all elements smaller than and equal to Kth smallest element.

**Examples:**

```
Input :  K = 3
              8
            /   \
           7     10
         /      /   \
        2      9     13
Output : 17
Explanation : Kth smallest element is 8 so sum of all
              element smaller then or equal to 8 are
              2 + 7 + 8

Input : K = 5
           8
         /   \
        5    11
      /  \
     2    7
      \
       3
Output :  25
```

```java
class Solution {
    int count = 0;
    int sum = 0;

    public int kthSmallest(TreeNode root, int k) {
        traverse(root, k);
        return sum;
    }

    public void traverse(TreeNode root, int k) {
        if (root == null)
            return;
        traverse(root.left, k);
        count++;
        if (count <= k)
            sum += root.val;
        if (count < k)
            traverse(root.right, k);
    }
}
```


---

# 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://mayanktyagi3111.gitbook.io/interview-prep/trees/sum-of-k-smallest-elements-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.
