230. Kth Smallest Element in a BST
We know that the in-order traversal sequence of a binary search tree is sorted, thus we can use it solve the problem.
/**
* 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 {
private:
void dfs(TreeNode* root, int& k, int& res) {
if (root == nullptr) {
return;
}
dfs(root->left, k, res);
k--;
if (k == 0) {
res = root->val;
return;
}
dfs(root->right, k, res);
}
public:
int kthSmallest(TreeNode* root, int k) {
int res = -1;
dfs(root, k, res);
return res;
}
};