【问题标题】:Kth Smallest Element in a BSTBST 中的第 K 个最小元素
【发布时间】:2015-10-23 08:28:54
【问题描述】:

我正在尝试一个 leetcode 问题 - find the kth smallest element in a binary search tree。我认为我写的解决方案是正确的,但它并没有通过所有的测试用例,我无法弄清楚我哪里出错了。以下是我的解决方案:

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)

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

【问题讨论】:

  • 使用列表文字作为默认参数 (array=[]) 是一个常见的问题。该数组在定义函数时创建一次,然后对每个未显式传递array 的函数调用使用相同的数组引用。可能与它有关。
  • 我不这么认为,因为我使用可视化编辑器 link 运行了一些输入,并且运行良好。

标签: python binary-search-tree binary-search


【解决方案1】:

BST 中的第 K 个最小元素

这是解决问题的算法:

  1. 编写返回 BST 节点的辅助方法。
  2. 在辅助方法中,按顺序遍历 BST 节点,沿途递减 k。
  3. 当 k 达到 1 时,将当前 BST 节点返回到原来的方法。
  4. 然后原始方法应返回此节点内的值。

Geeks for Geeks 有更多关于 The Kth Smallest Element in a BST problem 的信息。

【讨论】:

    猜你喜欢
    • 2020-03-02
    • 2019-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多