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?
Hint:
Try to utilize the property of a BST.
What if you could modify the BST node’s structure?
The optimal runtime complexity is O(height of BST).
解法1: In-order traversal O(N), N is number of elements
这题可以看成是一个in-order traversal的直接应用,因为BST的in-order traversal是一个有序数组,那么我们就可以根据这个性质,对数进行遍历直到找到第k个node。
C++
Java
Follow up : O(logN)
参考这篇文章的思路
如果可以修改每一个tree的node的结构,而使其保存leftcount和totalcount。那么一开始建立树需要O(N)的时间,而之后每一次insert和查找则只需要O(logN)的时间。