您的位置:首页 > 编程语言 > Go语言

[LeetCode] Algorithms-45. 230. Kth Smallest Element in a BST

2018-01-13 20:02 246 查看

描述:

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?

思路:

对于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) {
stack <TreeNode *> par;
TreeNode *cur = root;
int tem = 0;

while(cur || !par.empty()) {
while(cur) {
par.push(cur);
cur = cur->left;
}
cur = par.top();
if(--k == 0) return cur->val;
par.pop();
cur = cur->right;
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: