題目鏈接
tag:
- Medium统翩;
- Stack妥泉;
question:
??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.
Example 1:
Input: root = [3,1,4,null,2], k = 1
3
/ \
1 4
\
2
Output: 1
Example 2:
Input: root = [5,3,6,2,4,null,null,1], k = 3
5
/ \
3 6
/ \
2 4
/
1
Output: 3
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
的性質(zhì)來解題跌宛,最重要的性質(zhì)是就是左<根<右它改,那么如果用中序遍歷所有的節(jié)點就會得到一個有序數(shù)組患亿。所以解題的關鍵還是中序遍歷啊。關于二叉樹的中序遍歷可以參見我之前的博客Binary Tree Inorder Traversal 二叉樹中序遍歷厚脉,我們來看一種非遞歸的方法习寸,中序遍歷最先遍歷到的是最小的結點,那么我們只要用一個計數(shù)器器仗,每遍歷一個結點融涣,計數(shù)器自增1,當計數(shù)器到達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 cnt = 0;
stack<TreeNode*> sk;
TreeNode* p = root;
while (p || !sk.empty()) {
while (p) {
sk.push(p);
p = p->left;
}
p = sk.top();
sk.pop();
++cnt;
if (cnt == k)
return p->val;
p = p->right;
}
return 0;
}
};