LeetCode 230 Medium BST找第K大的数 Python

75 篇文章 0 订阅
72 篇文章 0 订阅

    My Method 1

    算法:暴力

    思路

        BST的特征是有序,中序遍历BST就可以得到一个有序序列,那么这个有序序列的第k个位置的数就是答案

        所以中序遍历BST,并且将遍历的节点值append 到数组,数组长度等于k时达到要求,return,停止递归

        ans中的k-1数就是答案

    复杂度分析:

        时间:OK,遍历到第K个节点

        空间:OK,递归栈

def kthSmallest(self, root, k):

    ans = []

    def inorder(root):

        if root == None:

            return None

        inorder(root.left)

        ans.append(root.val)

        if len(ans) == k:

            return

        inorder(root.right)

    inorder(root)

    return ans[k - 1]

    My Method 2

    用非递归的方式中序遍历BST,

    则递归的第k次的数就是目标值

def kthSmallest1(self, root, k):

    stack = []

    counter = 0

    while root or stack:

        while root:

            stack.append(root)

            root = root.left

        root = stack.pop()

        counter += 1

        if counter == k:

            return root.val

        root = root.right

    return None

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值