【问题标题】:Creating a BinarySortTree method that returns items in a sorted fashion创建以排序方式返回项目的 BinarySortTree 方法
【发布时间】:2021-03-18 16:41:51
【问题描述】:
def items(self) -> List:
    """Return all of the items in the BST in sorted order.

    >>> BinarySearchTree(None).items()  # An empty BST
    []
    >>> bst = BinarySearchTree(7)
    >>> left = BinarySearchTree(3)
    >>> left._left = BinarySearchTree(2)
    >>> left._right = BinarySearchTree(5)
    >>> right = BinarySearchTree(11)
    >>> right._left = BinarySearchTree(9)
    >>> right._right = BinarySearchTree(13)
    >>> bst._left = left
    >>> bst._right = right
    >>> bst.items()
    [2, 3, 5, 7, 9, 11, 13]
    """
    if self.is_empty():
        return []
    elif self._root:
        lst = [self._root]
        if self._left != BinarySearchTree(None):
            lst.insert(lst.index(self._root) - 1, self._left._root)
            self._left.items()
        if self._right != BinarySearchTree(None):
            lst.insert(lst.index(self._root) + 1, self._right._root)
            self._right.items()

    return lst

我的代码有什么问题?我正在尝试递归,它成功地通过了文档字符串示例并返回 [3, 7, 11]。我似乎无法实现代码的实际 recursion 部分,因此它返回更多。

注意:我正在尝试完成此方法不转储数字然后对列表进行排序

【问题讨论】:

  • 当你用self._{left,right}.items()递归时你不会使用结果,你也没有将lst对象传递给递归,所以递归的每一步都会创建自己的lst最终实际上什么也没做。我认为您需要像 child_items = self._left.items() 这样的东西,然后也将它们附加到 lst,我认为您不需要附加 self._left.root 的行,因为该根应该由递归返回。
  • BinarySearchTree 未定义。
  • @ScottHunter 你的评论有什么意义? items() 显然是该类的方法的定义,他只是没有包含类定义的其余部分。

标签: python binary-search-tree


【解决方案1】:

假设 BinarySearchTree 被定义为整个树的所有者,并且它的根属性是一个适当的 TreeNode,具有左右层次结构的 TreeNode(即不是另一个 BinarySearchTree,这没有任何意义),

你可以把它变成一个递归生成器:

def items(self):
    def DFS(node):
        if node.left: yield from DFS(node.left)   # all smaller nodes
        yield node                                # this node
        if node.right: yield from DFS(node.right) # all larger nodes
    return [] if self.is_empty() else list(DFS(self.root))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-06
    • 1970-01-01
    • 1970-01-01
    • 2013-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多