【发布时间】: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