在搜索二叉树中找到第K小的数。
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?
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
算法:由于搜索二叉树的中序遍历序列的从小到大排序的,所以只要找到中序遍历序列的第K个数即可:
1 |
public int count = 0; |
近期评论