# leetcode 230: Kth Smallest Element in a BST

### Kth Smallest Element in a BST

Total Accepted: 3655 Total Submissions: 12149

Given a binary search tree, write a function kthSmallest to find thekth 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?

[思路]

Follow up 挺有意思, 需要在节点中保留一些额外的信息: 左子树的大小. 在插入删除时也要同时维护左子树的大小. 再查找时,可以用二分. 时间复杂度为O(h)

[CODE]

/**
* 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 n = root;
while(n.left!=null) {
stack.push(n);
n = n.left;
}

while(k>0 && (n!=null || !stack.isEmpty())) {
if(n==null) {
n = stack.pop();
if(--k==0) return n.val;
n = n.right;
} else {
stack.push(n);
n = n.left;
}
}
return n.val;
}
}

• 本文已收录于以下专栏：

## LeetCode-230. Kth Smallest Element in a BST (JAVA)二叉树第k小的数字

LeetCode-230. Kth Smallest Element in a BST (JAVA)二叉树第k小的数字

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

## 【Leetcode】Kth Smallest Element in a BST

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

## [LeetCode]493. Reverse Pairs

https://leetcode.com/problems/reverse-pairs/?tab=Description 找出满足i 2 * nums[j]的所有对数 树状数...
• gqk289
• 2017年02月25日 16:33
• 928

## Leetcode493——Reverse Pairs

• emmaczw
• 2017年09月10日 09:25
• 96

## 【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
• 293

## 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 230: Kth Smallest Element in a BST 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)