码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 230. Kth Smallest Element in a BST

时间:2017-01-05 07:50:54      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:tin   ons   self   str   递归   pen   val   arch   binary   

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

标签:tin   ons   self   str   递归   pen   val   arch   binary   

原文地址:http://www.cnblogs.com/lettuan/p/6250981.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!