链接:https://leetcode.com/problems/kth-smallest-element-in-a-bst/
题目:求BST第k小元素
思路:中序遍历,然后计数。
代码:
class Solution {
public:
void order(TreeNode *root,int k){
if(!root || num > k) return;
order(root->left,k);
if(num == k) ret = root->val; //找到第k小元素
num++; //计数
order(root->right,k);
}
int kthSmallest(TreeNode* root, int k) {
num = 1;
order(root,k);
return ret;
}
private:
int ret;
int num;
};