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

230. Kth Smallest Element in a BST ——迭代本质:a=xx1 while some_condition: a=xx2

时间:2016-12-18 22:58:18      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:kth   sum   search   return   nbsp   blog   modified   object   tree   

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?

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def kthSmallest(self, root, k):
        """
        :type root: TreeNode
        :type k: int
        :rtype: int
        """
        # left first
        node = root
        nodes = []
        n = 0
        while node:
            nodes.append(node)
            node = node.left        
        while nodes:
            node = nodes.pop() # min val
            n += 1
            if n == k:
                return node.val
            node = node.right
            while node:
                nodes.append(node)
                node = node.left
        return None
        

 

230. Kth Smallest Element in a BST ——迭代本质:a=xx1 while some_condition: a=xx2

标签:kth   sum   search   return   nbsp   blog   modified   object   tree   

原文地址:http://www.cnblogs.com/bonelee/p/6195514.html

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