【问题标题】:How would I set the default parent node to root in this binary tree in Python?如何在 Python 中将默认父节点设置为此二叉树中的根节点?
【发布时间】:2016-04-20 14:57:45
【问题描述】:

如何在 Python 中将这个二叉树的默认父节点设置为根节点?

我有以下内容,但它给出了以下错误。

class Tree:
  def __init__(self):
    self.root=None

  def insertNode(self,parentNode=self.root,node=None):
    if self.root is None:
      self.root=node

这是它给出的错误:

    def insertNode(self,parentNode=self.root,node=None):
NameError: name 'self' is not defined

提前致谢

【问题讨论】:

标签: python binary-search-tree


【解决方案1】:

self.root 不能作为参数进行评估。一个简单的方法是:

class Tree:
  def __init__(self):
    self.root=None

  def insertNode(self,parentNode=None,node=None):
    if parentNode is None:
      parentNode=self.root
    if self.root is None:
      self.root=node

但是无论如何,这对于二叉树来说是非常糟糕的。只需在你的树的纸上画一下,看看如何定义方法,或者你应该训练一个关于 python 中的类/对象的更简单的案例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多