题目:
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?
题意:
给定一棵二叉搜索树,求出这棵二叉搜索树中第k小的元素。提示:请利用二叉搜索树的性质。
代码:
# 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
"""
node_lis = [] #当做栈,存储节点
res = [] #存储节点的值
while root != None or len(node_lis) > 0 : #利用迭代的方式遍历二叉搜索树。因为二叉搜索树的性质,如果用中序遍历的方式遍历二叉搜索树,则得到的是一个递增的序列,正好满足题意
while root != None: #入栈,如果入栈的时候就处理节点值,则为先序遍历
node_lis.append(root)
root = root.left
if len(node_lis) > 0 : #出栈,出栈的时候才处理节点值,为先序遍历
root = node_lis[-1] #取出栈顶元素
node_lis.pop() #删除栈顶元素
res.append(root.val) #处理栈顶元素值
if len(res) == k : #满足返回条件,则返回,终止程序
return res[-1]
root = root.right #这步必须没有条件地赋值,如果要检查root.right非空时才赋值,则root还是栈顶元素,下一轮循环时又回到了之前的判断条件(之前栈顶元素被判断过是否要入栈),因此,必须修改root为新的节点root.right,再进入下一轮循环
笔记:
之前在出栈时root的赋值处纠结了半天,不过,现在终于弄清楚了。
Python的list类型删除末尾元素:lis.pop()