leetcode_230. Kth Smallest Element in a BST 求二叉搜索树中的第k小的元素,中序遍历法

 题目:

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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值