首页 > 代码库 > 230. Kth Smallest Element in a BST ——迭代本质:a=xx1 while some_condition: a=xx2
230. Kth Smallest Element in a BST ——迭代本质:a=xx1 while some_condition: a=xx2
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。