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:

    1. Try to utilize the property of a BST.
    2. What if you could modify the BST node's structure?
    3. The optimal runtime complexity is O(height of BST).

链接:  http://leetcode.com/problems/kth-smallest-element-in-a-bst/

7/25/2017

2ms, 20%

好几天终于有道自己做的题了。。。iterative inorder traversal

 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 }

别人的答案

可以利用DFS求root的count,然后再从左右两边找

https://discuss.leetcode.com/topic/17810/3-ways-implemented-in-java-python-binary-search-in-order-iterative-recursive

python generator

https://discuss.leetcode.com/topic/18279/pythonic-approach-with-generator

更多讨论

https://discuss.leetcode.com/category/238/kth-smallest-element-in-a-bst

posted @ 2017-07-25 19:44  panini  阅读(265)  评论(0编辑  收藏  举报