230. Kth Smallest Element in a BST
problem description
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.
Example 1:
Example 2:
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?
algorithm thought
得到第k个数,这里其实可以利用之前得到数组中k大的数的解法。只是之前那个是要用O(n)时间将第k个数归位,这里是用O(n)时间得到当前root是第几大的数。对于BST来说,只要得到左子节点位置即可
code
algorithm analysis
最坏情况下时间复杂度还是需要O(n)时间。
Last updated