> For the complete documentation index, see [llms.txt](https://hao-fu-1.gitbook.io/oj/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://hao-fu-1.gitbook.io/oj/binary_tree_and_divide_conquer/binary-search-tree/kth-smallest-element-in-a-bst.md).

# Kth Smallest Element in a BST

<https://leetcode.com/problems/kth-smallest-element-in-a-bst/description/>

```
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?
```

## Thoughts

看到bst先想到中序遍历能有序，找第k个正好利用到这个性质。

## Code

```
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    private void pushLeft(Stack<TreeNode> stack, TreeNode node) {
        while (node != null) {
            stack.push(node);
            node = node.left;
        }
    }

    public int kthSmallest(TreeNode root, int k) {
        int res = 0;
        Stack<TreeNode> stack = new Stack<>();
        pushLeft(stack, root);
        while (!stack.isEmpty() && k > 0) {
            TreeNode node = stack.pop();
            k--;
            res = node.val;
            pushLeft(stack, node.right);
        }
        return res;
    }
}
```

## Analysis

花费10min.

Errors:

1. index初始化成了-1

时间复杂度为遍历所需O(n)。
