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个叶子节点,这样需要开辟新的空间,而且时间复杂度是O(N)
第二个就是求一个节点左边有多少个节点,那么他是第几个。这样的时间复杂度也达不到要求
顺着第二个思路想下去,如果我直接先到最左边的节点,然后倒着过来,就可以得到我想要的解了
/**
* 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;
TreeNode* temp = root;
while (temp || !st.empty()) {
while (temp) {
st.push(temp);
temp = temp->left;
}
temp = st.top();
if(--k == 0) {
return temp->val;
}
st.pop();
temp = temp->right;
}
}
};