Leetcode 230. Kth Smallest Element in a BST

Posted lettuan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 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?

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

 1 class Solution(object):
 2     def kthSmallest(self, root, k):
 3         """
 4         :type root: TreeNode
 5         :type k: int
 6         :rtype: int
 7         """
 8         ans = []
 9         stack = []
10         
11         while stack or root:
12             while root:
13                 stack.append(root)
14                 root = root.left
15             root = stack.pop()
16             ans.append(root.val)
17             if len(ans) == k:
18                 return ans[-1]
19             root = root.right
20         return ans[-1]

 



以上是关于Leetcode 230. Kth Smallest Element in a BST的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 230. Kth Smallest Element in a BST

Leetcode 230. Kth Smallest Element in a BST

Leetcode 230: Kth Smallest Element in a BST

leetcode 230. Kth Smallest Element in a BST

[Leetcode] Binary search/tree-230. Kth Smallest Element in a BST

[LeetCode] 230. Kth Smallest Element in a BST