Given a binary search tree, write a function
kthSmallest
to find the kth smallest element in it.
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?
Constraints:
- The number of elements of the BST is between
1
to10^4
.- You may assume
k
is always valid,1 ≤ k ≤ BST's total elements
.
給予一個二元搜索樹(BST),寫一個程式
kthSmallest
可以找出裡面第k小的元素。
進階:
如果這個BST很常被更改(插入/刪除),且你也很常需要找到第k小的元素該怎麼辦?你可以優化到常數時間內嗎?
限制:
- BST中的元素介於
1
到10^4
之間。- 你可以假設
k
總是合法,1 ≤ k ≤ BST's total elements
。
k--
,跑到k == 0
的時候將該節點的值取出即可。LeetCode
C++