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.
Example 1:
Input: root = [3,1,4,null,2], k = 1 3 / \ 1 4 \ 2 Output: 1
Example 2:
Input: root = [5,3,6,2,4,null,null,1], k = 3 5 / \ 3 6 / \ 2 4 / 1 Output: 3
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?
给定一个二叉搜索树,求出其第K大的元素。二叉搜索树是一种满足左子树所有节点值<根节点<右子树所有节点值的一种二叉树。因此,求其第K大元素即中序遍历其第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) {
stack<TreeNode*> st_node;
TreeNode* p = root;
while(p != nullptr || !st_node.empty())
{
if(p != nullptr)
{
st_node.push(p);
p = p->left;
}
else
{
p = st_node.top();
st_node.pop();
k--;
if(0 == k)
{
return p->val;
}
p = p->right;
}
}
return NULL;
}
};