leetcode - 230. 二叉搜索树中第K小的元素
题目
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/d8d981797be788d50dc8918b87860792.png)
代码
#include <iostream>
#include <vector>
using namespace std;
typedef struct TreeNode{
int val;
struct TreeNode *left, *right;
}TreeNode, *BiTree;
void create(BiTree &root){
int tn;
cin>>tn;
if(tn == -1){
root = NULL;
return;
}
root = new TreeNode;
root->val = tn;
create(root->left);
create(root->right);
}
vector<int> nums;
void inorder(TreeNode *root){
if(!root){
return;
}
inorder(root->left);
nums.push_back(root->val);
inorder(root->right);
}
int kthSmallest(TreeNode* root, int k) {
inorder(root);
return nums[k-1];
}
int main(){
int k, res;
cin>>k;
TreeNode* root;
create(root);
res = kthSmallest(root, k);
cout<<res;
return 0;
}