## 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.

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).

### 分析

• k == root.leftCnt+1, 则返回root
• k > node.leftCnt, 则 k -= root.leftCnt+1, root=root.right
• 否则，node = node.left

### 解法1

// Kth Smallest Element in a BST
// Time Complexity: O(k), Space Complexity: O(h)
public class Solution {
public int kthSmallest(TreeNode root, int k) {
Stack s = new Stack<>();
TreeNode p = root;

while (!s.empty() || p != null) {
if (p != null) {
s.push(p);
p = p.left;
} else {
p = s.pop();
--k;
if (k == 0) {
return p.val;
}
p = p.right;
}
}
return -1;
}
}