Py学习  »  Python

如何在python中进行树遍历

Michael Torres • 3 年前 • 991 次点击  

所以我遇到了一些让我目瞪口呆的问题。我不明白我的代码哪里出了问题,但我的想法是检查我所在的当前节点是否正确 None 如果是的话,我会在 整齐 , 预购 邮购 .这是我的密码

class Node:
  def __init__(self, data):
    self.data = data
    self.left = None
    self.right = None

  def inOrder(self, arr=[]):
    if self is not None:
      self.left.inOrder(arr)
      arr.append(self.data)
      self.right.inOrder(arr)

    return arr

当我运行它时,我得到一个错误 self.left.inOrder() AttributeError: 'NoneType' object has no attribute 'inOrder' 我不知道为什么。我正在检查 self is not None 这难道不能保证我 Node 有一个 left right .

我只是在展示 为了 我已经实施了。

我通过以下方法解决了这个问题

class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

    def inOrder(self):
        if self is not None and self.left is not None:
            self.left.inOrder()

        print(self.data)

        if self is not None and self.right is not None:
            self.right.inOrder()


root = Node(1)
root.left = Node(2)
root.right = Node(3)


root.inOrder()

无论我是将其保存到列表中还是打印出来,我都可以,但如果我已经检查self是否为None,那么我就不能打电话吗 self.left.inOrder self.right.inOrder ?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/132125
 
991 次点击  
文章 [ 1 ]  |  最新文章 3 年前