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.
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?
==============================================================
题目链接:https://leetcode.com/problems/kth-smallest-element-in-a-bst/
题目大意:找出二叉搜索树第K小的元素。
思路:中序遍历,找到直接结束。
参考代码:
/**
* 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 ans ;
findKth ( root , k , ans ) ;
return ans ;
}
bool findKth( TreeNode* root , int& k , int& ans )
{
if ( root == NULL )
return false ;
if ( findKth ( root -> left , k , ans ) )
return true ;
if ( k == 1 )
{
ans = root -> val ;
return true ;
}
k -- ;
return findKth ( root -> right , k , ans ) ;
}
};