# [leetcode] 230.Kth Smallest Element in a BST

262人阅读 评论(0)

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.

What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?

/**
* 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 {
public:
int kthSmallest(TreeNode* root, int k) {
if(root == NULL)return 0;
int value = 0;
int index = 0;
InOrder(root, k, value, index);
return value;
}
void InOrder(TreeNode* root, int k, int& value, int& before) {
if(root == NULL)return;
InOrder(root->left, k, value, before);
before++;
if(before == k){
value = root->val;
before = k;
return;
}
else if(before > k)return;
InOrder(root->right, k, value, before);
}
};
0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：51556次
• 积分：2793
• 等级：
• 排名：第12799名
• 原创：239篇
• 转载：0篇
• 译文：0篇
• 评论：5条
文章分类
最新评论