Description:
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?
思路:
二叉搜索树是一种特殊的二叉树,具有以下性质:
**1. 如果左子树不为空,左子树上结点的值均小于根节点的值
2. 如果右子树不为空,右子树结点上的值均大于根节点的值
3. 左右子树也分别为二叉搜索树**
通过性质我们得知,左子树<根节点<右子树。我们学过三种树的遍历,中序遍历,则刚好是从左子树到根节点到右子树遍历,即可得到一个递增的序列,然后找到第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 result = 0;
int index = 0;
if(k < 1)
return -1;
InOrder(root, k, index, result);
return result;
}
void InOrder(TreeNode *root, int k, int &index, int &result) {
if (root) {
InOrder(root->left, k, index, result);
index++;//计数
if (index == k) {
result = root->val;
}
InOrder(root->right, k, index, result);
}
}
};
非递归方法:
class Solution { //非递归方法:
public:
int kthSmallest(TreeNode *root, int k) {
int index = 0;
TreeNode *cur = root;
stack<TreeNode*> s;
while (cur || !s.empty()){
while (cur){
s.push(cur);
cur = cur->left;
}
cur = s.top(); //返回栈顶元素
s.pop();
index++;
if (index == k)
return cur->val;
cur = cur->right;
}
return 0;
}
};