Leetcode 230. Kth Smallest Element in a BST

时间:2024-01-08 15:10:50

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?

本题和不用递归的方法中序遍历BST (Leetcode 94题) 基本上一样。我们只要在iteratively的过程中输出第K个val就可以了。

 class Solution(object):
def kthSmallest(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: int
"""
ans = []
stack = [] while stack or root:
while root:
stack.append(root)
root = root.left
root = stack.pop()
ans.append(root.val)
if len(ans) == k:
return ans[-1]
root = root.right
return ans[-1]