原文地址:http://blog.csdn.net/brucehb/article/details/46734301
iven 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.
Follow up:
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) {
int n=0;
int val=0;
visit(root,k,val,n);
return val;
}
private:
void visit(TreeNode* node,int k,int &val,int &n)
{
if(node==NULL)
return;
visit(node->left,k,val,n);
if (n < k)
{
n += 1;
if (n == k)
{
val = node->val;
return;
}
}
visit(node->right,k,val,n);
}
};