# 230. Kth Smallest Element in a BST

## 1.問題

* 找出第K小的element

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LJdYsG3YUWxY_q1CXpA%2F-LJd_VfbGBj8Cno40pVR%2F2018081108.jpg?alt=media\&token=dc5c3e3e-8f9c-43a0-96c1-76ceb5a3c5f8)

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

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LJdYsG3YUWxY_q1CXpA%2F-LJd_Don4LleHmRtkgiF%2F2018081107.jpg?alt=media\&token=24e141a1-54ad-46fb-8382-678d525877ee)
