# 230. Kth Smallest Element in a BST

## 1.問題

* 找出第K小的element

![](/files/-LJd_VfbGBj8Cno40pVR)

## 2.想法

* 以inorder尋覽BST後會得到排序的list

## 3.程式碼

```
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int kthSmallest(TreeNode* root, int k) {
        vector<int> v;
        inOrder(root, v);
        
        return v[k - 1];
    }
private:
    void inOrder(TreeNode* root, vector<int>& v) {
        
        if (root != NULL)
        {
            inOrder(root->left, v);
            v.push_back(root->val);
        inOrder(root->right, v);
        }
        
    }
};
```

## 4.Performance

![](/files/-LJd_Don4LleHmRtkgiF)


---

# 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://jenhsuan.gitbook.io/algorithm/leetcode/230.-kth-smallest-element-in-a-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.
