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?
Hint:
如果每次用递归来计算左子树或右子树的结点个数,类似于二分法,但每次计算左子树节点个数会有很多重复开销;如果按照提示,改变TreeNode的存储结构,再添加一个leftCount属性,那么就比较容易计算出结果了。
下面提供了一种用stack来保存节点的方法,思想是将节点入栈,保证从最小节点开始遍历直到找到第k个,时间复杂度是O(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; 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; } } };