【问题标题】:represent binary search trees in python在python中表示二叉搜索树
【发布时间】:2011-03-04 18:33:19
【问题描述】:

如何在 python 中表示二叉搜索树?

【问题讨论】:

  • 你能说得更具体点吗?你想做什么?
  • 为了学习,我正在尝试构建一个二叉搜索树。

标签: python data-structures binary-tree binary-search-tree


【解决方案1】:
class Node(object):

  def __init__(self, payload):
    self.payload = payload
    self.left = self.right = 0

    # this concludes the "how to represent" asked in the question.  Once you
    # represent a BST tree like this, you can of course add a variety of
    # methods to modify it, "walk" over it, and so forth, such as:

  def insert(self, othernode):
    "Insert Node `othernode` under Node `self`."
    if self.payload <= othernode.payload:
      if self.left: self.left.insert(othernode)
      else: self.left = othernode
    else:
      if self.right: self.right.insert(othernode)
      else: self.right = othernode

  def inorderwalk(self):
    "Yield this Node and all under it in increasing-payload order."
    if self.left:
      for x in self.left.inorderwalk(): yield x
    yield self
    if self.right:
      for x in self.right.inorderwalk(): yield x

  def sillywalk(self):
    "Tiny, silly subset of `inorderwalk` functionality as requested."
    if self.left:
      self.left.sillywalk()
    print(self.payload)
    if self.right:
      self.right.sillywalk()

等等——基本上就像使用引用而不是指针的任何其他语言一样(例如 Java、C# 等)。

编辑

当然,sillywalk 的存在确实很愚蠢,因为完全相同的功能是在 walk 方法之上的单线外部 sn-p:

for x in tree.walk(): print(x.payload)

使用walk,您可以在nodes-in-order 流上获得几乎任何其他功能,而使用sillywalk,您可以获得几乎diddly-squat。但是,嘿,OP 说 yield 是“令人生畏的”(我想知道 Python 2.6 的其他 30 个关键字中有多少在 OP 的判断中值得这样吓人的话?-)所以我希望 print 不是!

这完全超出了实际问题,关于代表 BST:那个问题完全在__init__ 中得到回答——payload 属性包含节点的有效负载,leftright 属性来保存None(意思是,该节点在该侧没有后代)或Node(在适当一侧的后代子树的顶部)。当然,BST 约束是每个节点的每个左后代(如果有)的有效载荷小于或等于所讨论节点的有效载荷,每个右后代(同样,如果有的话)都有更大的有效载荷——我添加了 @ 987654335@ 只是为了说明维持该约束是多么微不足道,walk(现在是 sillywalk)表明让所有节点按有效负载的递增顺序是多么微不足道。同样,总体思路与您在任何使用引用而不是指针的语言(例如 C# 和 Java)中表示 BST 的方式相同。

【讨论】:

  • 你应该把它隔开一点,这样一起读起来很难。
  • @Alex Yield !!! :|我相信对于像我这样的新手来说,没有比这更令人生畏的解决方案了。
  • @Bunny,Python 的关键字确实很少(从 2.6 开始是 31 个)——在这个小数字中,您觉得哪些关键字“令人生畏”?无论如何,我将添加一个完全愚蠢和毫无意义的类似步行的方法(基本上就像walk 一样工作,但以一种非常受限制的方式)如果这让你开心(并添加空格让@detly 也开心) -相应地编辑 A。
  • @Bunny - 不要以为yield 很难,因为它在其他语言中并不常见。写几个 DIY 例子,我相信它会变得更清晰。
  • @Alex:在 __init__() 中使用 0 而不是 None 有什么特别的原因吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-20
相关资源
最近更新 更多