題目:java
Given a binary search tree, write a function kthSmallest
to find the kth smallest element in it.node
Note:
You may assume k is always valid, 1 ≤ k ≤ BST's total elements.python
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?app
Hint:spa
連接: http://leetcode.com/problems/kth-smallest-element-in-a-bst/code
7/25/2017blog
2ms, 20%element
好幾天終於有道本身作的題了。。。iterative inorder traversalleetcode
1 public class Solution { 2 public int kthSmallest(TreeNode root, int k) { 3 Stack<TreeNode> stack = new Stack<>(); 4 TreeNode node = root; 5 int kthSml = 0; 6 7 while((node != null || !stack.isEmpty()) && k > 0) { 8 while (node != null) { 9 stack.push(node); 10 node = node.left; 11 } 12 node = stack.pop(); 13 kthSml = node.val; 14 k--; 15 node = node.right; 16 } 17 return kthSml; 18 } 19 }
別人的答案get
能夠利用DFS求root的count,而後再從左右兩邊找
python generator
https://discuss.leetcode.com/topic/18279/pythonic-approach-with-generator
更多討論
https://discuss.leetcode.com/category/238/kth-smallest-element-in-a-bst