230 Kth Smallest Element in a BST
Given a binary search tree, write a functionkth Smallest
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 kth Smallest 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).
解法一:脑残的我只能想到中序遍历然后一个一个数O(n)。解法二是来自leetcode discuss里的二分做法O(height),感觉有点像4 Median of Two Sorted Arrays那题。解法一:T:O(n),S:O(n),解法二:T:O(height)平均,O(N^2) worst,S:O(height),空间是递归的深度
Last updated