230. Kth Smallest Element in a BST
题目:
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:
Try to utilize the property of a BST.
What if you could modify the BST node’s structure?
The optimal runtime complexity is O(height of BST).
链接: http://leetcode.com/problems/kth-smallest-element-in-a-bst/
方法1:
用173题的思路,implement一个iterator。时间复杂度是O(h),空间复杂度是O(h),因为有可能需要遍历右孩子的左子树path?
code
方法2: iterative
边记录边入栈,不需要全部入栈,利用count来记录已获取node的数量。这样当提前取满的时候就可以退出,否则inorder traversal全部需要O(n)
code
犯过的错:
- inorder traversal 练的不熟
- 被quote掉的循环造成k在循环内清零
class Solution {
public:
int kthSmallest(TreeNode* root, int k) {
int result;
stack<TreeNode*> myStack;
while(k > 0){
if (root){
myStack.push(root);
root = root->left;
}
else{
//while(!myStack.empty()){
if (myStack.empty()) break;
root = myStack.top();
myStack.pop();
result = root->val;
k--;
// if (root != nullptr){
root = root->right;
//}
// }
}
}
return result;
}
};
方法3: recursion
剪枝
code
public class Solution {
List<Integer> nodeVal = new ArrayList<Integer>();
public int kthSmallest(TreeNode root, int k) {
if(root == null)
return 0;
inorder(root, k);
return nodeVal.get(k - 1);
}
private void inorder(TreeNode root, int k) {
if(nodeVal.size() >= k)
return;
if(root == null)
return;
inorder(root.left, k);
nodeVal.add(root.val);
inorder(root.right, k);
}
}
或者
public class Solution {
private int count = 0;
private int res = 0;
public int kthSmallest(TreeNode root, int k) {
if(root == null)
return 0;
inorder(root, k);
return res;
}
private void inorder(TreeNode root, int k) {
if(root == null)
return;
if(count >= k)
return;
inorder(root.left, k);
if(count >= k)
return;
res = root.val;
count++;
inorder(root.right, k);
}
}