在这种情况下,它要求我进行间接递归。用于“ def count_less”功能。这意味着计算小于给定值的节点数。对于我的代码,我将具有attributeError。谁能帮我检查我的代码?
class BST:
"""A Binary Search Tree."""
def __init__(self, container=[]):
"""(BST, list) -> NoneType
Initialize this BST by inserting the items from container (default [])
one by one, in the order given.
"""
# Initialize empty tree.
self.root = None
# Insert every item from container.
for item in container:
self.insert(item)
def __str__(self):
"""(BST) -> str
Return a "sideways" representation of the values in this BST, with
right subtrees above nodes above left subtrees and each value preceded
by a number of TAB characters equal to its depth.
"""
if self.root:
return self.root._str("")
else:
return ""
def count_less(self, item):
"""(BST, object) -> int
Return the number of items in this BST that are strictly less than
item.
"""
if self.root:
return self.root.count_less(item)
else:
return 0
我需要在“ _BSTNode”类中编写函数体,并在“ BST”类中调用该类方法。
class _BSTNode:
"""A node in a BST."""
def __init__(self, item, left=None, right=None):
"""(_BSTNode, object, _BSTNode, _BSTNode) -> NoneType
Initialize this node to store item and have children left and right.
"""
self.item = item
self.left = left
self.right = right
def _str(self, indent):
"""(_BSTNode, str) -> str
Return a "sideways" representation of the values in the BST rooted at
this node, with right subtrees above nodes above left subtrees and each
value preceded by a number of TAB characters equal to its depth, plus
indent.
"""
if self.right:
right_str = self.right._str(indent + "\t")
else:
right_str = ""
if self.left:
left_str = self.left._str(indent + "\t")
else:
left_str = ""
return right_str + indent + str(self.item) + "\n" + left_str
def count_less(self: '_BSTNode', item: object) -> int:
"""
Return the number of items in the BST rooted at this node that are
strictly less than item.
"""
if not self.item:
return 0
elif item <= self.item:
if self.left:
return 1 + self.left.count_less(item)
return 0
elif self.item < item:
if self.left and self.right:
return 1 + self.left.count_less(item) + self.right.count_less(item)
elif self.left and not self.right:
return 1 + self.left.count_less(item)
elif self.right and not self.left:
return 1 + self.right.count_less(item)
else:
return 1
这是我输入的示例,输出中出现错误。
>>> t = BST(container=[5,1,2,3,4,6,7,8,9])
>>> t.count_less(10)
答案 0 :(得分:1)
您可以依靠None
的虚假性质,并使用if
语句检查子节点是否存在。我非常确定以下代码不会返回正确的答案:如果self.item == item
会发生什么?左侧和右侧子级的子级都有可能小于item
参数。
elif item < self.item:
if self.left:
return 1 + self.left.count_less(item)
return 1
elif item > self.item:
if self.right:
return 1 + self.right.count_less(item)
return 1