您的位置:首页 > 其它

230. Kth Smallest Element in a BST

2018-02-02 08:49 302 查看
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?

class Solution {
public:

int kthSmallest(TreeNode* root, int k) {
stack<TreeNode *> st;
TreeNode *p = root;
while(p || !st.empty())
{
while(p)
{
st.push(p);
p = p->left;
}
p = st.top();
if(--k == 0)
return p->val;
st.pop();
p = p->right;
}
}

};
int kthSmallest(TreeNode* root, int& k) {
if (root) {
int x = kthSmallest(root->left, k);
return !k ? x : !--k ? root->val : kthSmallest(root->right, k);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: