BST中第k个最小元素

2024-09-27 00:14:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试一个leetcode问题link来寻找二叉搜索树中第k个最小的元素。我认为我写的解决方案是正确的,但不知何故它并没有通过所有的测试用例,我也不知道我在哪里出错。以下是我的解决方案:

class Solution(object):
    def kthSmallest(self, root, k, array=[]):
        """
        :type root: TreeNode
        :type k: int
        :rtype: int
        """
        if root.left:
            return self.kthSmallest(root.left, k, array)
        array.append(root.val)
        if len(array) == k:
            return array[-1]
        if root.right:
            return self.kthSmallest(root.right, k, array)

谁能告诉我我的代码有什么问题吗?在


Tags: selfright元素returniftypelink测试用例

热门问题