/**
* 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:
int kthSmallest(TreeNode* root, int k) {
// 中序遍历计数
int count = 0;
int result = 0;
// 辅助函数进行中序遍历
inorderTraversal(root, k, count, result);
return result;
}
private:
// 中序遍历函数
void inorderTraversal(TreeNode* root, int k, int& count, int& result) {
// 如果节点为空或者已经找到第k小的元素,直接返回
if (root == nullptr || count >= k) {
return;
}
// 先遍历左子树
inorderTraversal(root->left, k, count, result);
// 访问当前节点
count++;
if (count == k) {
result = root->val;
return;
}
// 再遍历右子树
inorderTraversal(root->right, k, count, result);
}
};
/*
二叉搜索树的中序遍历就是升序的 左根右
*/