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?
Hint:
Try to utilize the property of a BST.
Solution:
class Solution(object):
def kthSmallest(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: int
"""
size_map = dict()
left_size = self.size(root.left, size_map)
if left_size + 1 == k:
return root.val
if left_size + 1 > k:
return self.kthSmallest(root.left, k)
return self.kthSmallest(root.right, k - left_size - 1)
def size(self, root, size_map):
if not root:
return 0
if root in size_map:
return size_map[root]
left = self.size(root.left, size_map)
right = self.size(root.right, size_map)
size = left + right + 1
size_map[root] = size
return size