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

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?

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int kthSmallest(TreeNode root, int k) {
Stack<TreeNode> stack =new Stack<TreeNode>();
int n=0;
int ans=0;
while(true){
while(root!=null){
stack.push(root);
root=root.left;
}
if(n<k){
n++;
TreeNode node=stack.pop();
root=node.right;
ans=node.val;
}
else{
return ans;
}

}
//return 0;
}
}
• 本文已收录于以下专栏：

## 【LEETCODE】230-Kth Smallest Element in a BST

Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. No...

## Leetcode 230. Kth Smallest Element in a BST (Medium) (cpp)

Leetcode 230. Kth Smallest Element in a BST (Medium) (cpp)
• Niko_Ke
• 2016年08月23日 11:17
• 296

## LeetCode 230. Kth Smallest Element in a BST 解题报告

LeetCode 230. Kth Smallest Element in a BST 解题报告

## leetcode-230-Kth Smallest Element in a BST

Kth Smallest Element in a BST   Given a binary search tree, write a function kthSmallest to ...

## <LeetCode OJ> 230. Kth Smallest Element in a BST

230. Kth Smallest Element in a BST My Submissions Question Total Accepted: 32753 Total Submissio...

## leetcode -- 230. Kth Smallest Element in a BST 【遍历 + 计数】

举报原因： 您举报文章：leetcode 230. Kth Smallest Element in a BST 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)