这是我的代码:
# 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 generateTrees(self, n):
"""
:type n: int
:rtype: List[TreeNode]
"""
if n==0:
return []
return self.generateTreesHelper(range(1, n+1))
def generateTreesHelper(self, lst):
if len(lst) == 0:
return [None]
elif len(lst) == 1:
return TreeNode(lst[0])
else:
res = []
for i in range(0, len(lst)):
left_trees = self.generateTreesHelper(lst[:i])
right_trees = self.generateTreesHelper(lst[i+1:])
for left in left_trees:
for right in right_trees:
root = TreeNode(lst[i])
root.left = left
root.right = right
res.append(root)
return res
代码用于生成存储值1 ... n的所有结构上唯一的BST(二叉搜索树)。
如果n = 3,程序应返回下面显示的所有5个唯一BST。
[[1,空值,如图2所示,空,3],[1,NULL,3,2],[2,1,3],[3,1,NULL,NULL,2],[3,2 ,空,1]]。
但是,我一直收到错误消息。
TypeError:' int'对象不可迭代。
答案 0 :(得分:2)
我不知道如何
TypeError: 'int' object is not iterable.
错误。在Python 2.6和3.6上,我都会收到问题标题中提到的错误:
TypeError: 'TreeNode' object is not iterable
这是因为return TreeNode(lst[0])
返回一个TreeNode。它应该返回包含该TreeNode的列表,以便可以在left_trees
和right_trees
for
循环中进行迭代。
这是代码的修复版本,使用简单的__repr__
方法,以便我们可以看到输出正确。
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def __repr__(self):
if self.left is None and self.right is None:
s = '{}'.format(self.val)
else:
s = '[val:{}, left:{}, right:{}]'.format(self.val, self.left, self.right)
return s
class Solution(object):
def generateTrees(self, n):
"""
:type n: int
:rtype: List[TreeNode]
"""
if n==0:
return []
return self.generateTreesHelper(range(1, n+1))
def generateTreesHelper(self, lst):
if len(lst) == 0:
return [None]
elif len(lst) == 1:
return [TreeNode(lst[0])]
else:
res = []
for i in range(0, len(lst)):
left_trees = self.generateTreesHelper(lst[:i])
right_trees = self.generateTreesHelper(lst[i+1:])
for left in left_trees:
for right in right_trees:
root = TreeNode(lst[i])
root.left = left
root.right = right
res.append(root)
return res
print(Solution().generateTrees(3))
<强>输出强>
[[val:1, left:None, right:[val:2, left:None, right:3]], [val:1, left:None, right:[val:3, left:2, right:None]], [val:2, left:1, right:3], [val:3, left:[val:1, left:None, right:2], right:None], [val:3, left:[val:2, left:1, right:None], right:None]]