【问题标题】:How to traverse a binary search tree in alphabetical order python? [closed]如何按字母顺序python遍历二叉搜索树? [关闭]
【发布时间】:2020-05-03 11:09:40
【问题描述】:

我需要你的帮助,或者你能给我一些建议。我真的很挣扎,一些帮助会很完美,所以这就是我到目前为止所得到的;

import BST, TreeNode

class Bibliography:

def __init__(self):
    self.bibtree = BST()

def getReference(self,key):
    """Return the reference for the key, if it exists, otherwise None."""
    theValue = self.bibtree.retrieveKey(key,self.bibtree.root)
    if theValue == None:
        return None
    else:
        return theValue.payload

def addReference(self, key, value):
    """Add the reference represented by key and value.

    Assume the key does not exist in the bibliography.
    """
    self.bibtree.insertNode(key, value)

def removeReference(self, key):
    """Remove the reference with this key.

    Assume the key exists in the bibliography.
    """
    self.bibtree.deleteNode(key)

def outputBibliography(self):
    """Return a string with all references in alphabetical order.

    There must be an empty line after each reference
    """
    return self.traverse(self.bibtree.root)

def traverse(self, aNode):
    """Return a string with the references in the subtree rooted at aNode.

    The references should be ordered alphabetically,
    with an empty line after each reference
    and a space between each key and its value. See the test file.
    """
    if aNode:
      self.traverse(aNode.leftChild)
        return str(aNode.key, aNode.payload, end='\n\n')
      self.traverse(aNode.right)

当我进行测试时,下面的函数不起作用并且需要帮助。它将它作为这个括号 [] 中的列表返回,我不想要这个。我也想要一个空行,这也不会发生。我不确定我做错了什么,如果您能给我一些建议,这将有所帮助。

def traverse(self, aNode):
    """Return a string with the references in the subtree rooted at aNode.

    The references should be ordered alphabetically,
    with an empty line after each reference
    and a space between each key and its value. See the test file.
    """
        res = []
        if aNode:
          res = self.traverse(aNode.leftChild)
          res.append(aNode.key + ' ' + aNode.payload + '\n\n')
          res = res + self.traverse(aNode.rightChild)
        return res

使用此代码的输出是:

['Adams, A (1991) Loves football\n\n', 'Marlow, C (1996) Loves cricket\n\n', 'Smith, I (1994) Does not play sports\n\n']

我想要这个输出:

Adams, A (1991) Loves football

Marlow, C (1996) Loves cricket

Smith, I (1994) Does not play sports

【问题讨论】:

  • 无法理解您要实现的目标,您只指定代码中发生的事情并且您不想要这种特定类型的输出,您所说的“您不想要”是什么意思想要这个”——那你想要什么?那么这篇文章的问题是什么?请提供示例代码和所需的解决方案。
  • 作业的“按字母顺序遍历二叉搜索树”部分希望您进行按顺序遍历 (en.wikipedia.org/wiki/Tree_traversal#In-order_(LNR))。你似乎已经解决了那部分。现在只是以作业要求的形式生成输出。
  • 您好,谢谢您的回复,您知道我该怎么做,所以 outputBibliography(self): 可以调用吗?
  • 好吧,您将返回字符串,而不是打印它。所以是这样的:def outputBibliography(self): return '\n\n'.join(self.traverse(self.bibtree.root))
  • 感谢您的快速回复,我无法触摸 def outputBibliography(self),只有 def traverse(self, aNode): 所以我应该添加 return '\n\n'.join(self .traverse(self.bibtree.root)) 到它呢?

标签: python function binary-search-tree traversal


【解决方案1】:

无论如何,您都在连接列表,如res + self.traverse(aNode.rightChild)。好吧,别管我以前的 cmets 了,即使有列表,你也会得到 O^2,因为你把它们都复制了一遍。就这样做

def traverse(self, aNode):
    res = ""
    if aNode:
        res = self.traverse(aNode.leftChild)
        res += aNode.key + ' ' + aNode.payload + '\n\n'
        res += self.traverse(aNode.rightChild)
    return res

这最终会在最后一个引用之后给你一个空行,所以它是赋值所说的更文字的实现:“......在每个引用之后都有一个空行......”。 join() 只会在引用之间插入换行符,而不是在最后一个之后。

【讨论】:

  • 感谢您的解决方案,您似乎知道很多。请问,如果我要添加重复键,我需要对 addReference 和 removeReference 函数进行哪些调整,以便大致了解。
  • 您不应该就 SO 提出“大”的后续问题。无论如何,这取决于您的 BST 课程是如何编写的。 addReferenceremoveReference 基本上都只是委托给 BST 中的 addNodedeleteNode。我现在正在阅读有关家庭作业问题政策的更多信息。meta.stackoverflow.com/questions/334822/…
  • 回答后续问题的最佳方法是尝试实施它。然后你会看到需要做什么才能使一切正常。 removeReference 应该删除所有重复的键,还是只删除“第一个”键?您想在重复键之间进行一些排序,例如它们应该按插入顺序打印吗? (稳定排序。)如果是这样,你在实现时必须考虑它,以满足这个属性。
  • 好的,谢谢您的帮助!我会继续努力解决这个问题,如果你有任何好的链接,请告诉我,因为网络上的信息都是不同的。
  • 你想帮助什么?一般的 Python 问题、编程技巧(例如,如何使用递归函数)或数据结构、计算机科学的东西?对于一般的 Python 问题,帮助我的是阅读 Python 教程“从头到尾”。它是 Python 文档 (docs.python.org/3) 链接教程的一部分。直接链接在这里docs.python.org/3/tutorial/index.html。它很长,但它很有帮助。我很喜欢learnpythonthehardway.org/book(在网络上免费),但我自己没有读过。
【解决方案2】:

你快到了。您的 traverse 方法会生成所需行的列表。唯一剩下的就是将该列表转换为单个字符串,其中行由'\n\n'分隔,即一个'\n'终止当前行,另一个'\n'给出一个空行。

tmp = tree.traverse(tree.root)  # tmp now contains the list ['Adams, A (1991) Loves football', 'Marlow, C (1996) Loves cricket', ...
print('\n\n'.join(tmp))

这会以您想要的形式打印输出。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-08
    • 1970-01-01
    • 2018-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多