题目链接:https://leetcode-cn.com/problems/kth-smallest-element-in-a-bst/
题目如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
//二叉搜索树的中序遍历为有序数列
vector<int> vtr;
int kthSmallest(TreeNode* root, int k) {
dfs(root);
return vtr[k-1];
}
void dfs(TreeNode* root){
if(root==NULL) return ;
if(root->left) dfs(root->left);
vtr.push_back(root->val);
if(root->right) dfs(root->right);
}
};