题目描述:
Given a binary search tree, write a function kthSmallest
to find the kth smallest element in it.
Note:
You may assume k is always valid, 1 ≤ k ≤ BST's total elements.
考虑二叉搜索树的性质:中序遍历是递增有序的,因此可以中序遍历该二叉搜索树,找到第K个节点即可
AC代码如下:
class Solution {
public:
int kthSmallest(TreeNode* root, int k) {
if (root == NULL) return 0;
int ans;
inorder(root, k, ans);
return ans;
}
void inorder(TreeNode* root, int& k,int& num){
if (k == 0) return;
if (root->left != NULL){
inorder(root->left, k,num);
}
k--;
if (0== k) num=root->val;
if (root->right != NULL){
inorder(root->right, k,num);
}
}
};