将遍历写入python3.x版本中的文件



我试图遍历一个堆,并将遍历写入一个文件,但我失败了。

当我只想在文件中打印出节点时,我一直遇到最大遍历深度的问题。

我认为您的代码应该更像这样:

def inorder(self, file):    
    if self._left is not None:
        file.write(str(self) + ' ')
        self._left.inorder(file)
    file.write(str(self) + ' ')
    if self._right is not None:
        file.write(str(self) + ' ')
        self._right.inorder(file)

注意:

  1. 要写入的file是一个参数,传递给递归调用,而不是每次都传递open
  2. 身份不平等检测None;以及
  3. 我假设您有一个树结构,其中self._leftself._rightself是同一类的实例(由于您提供的类太少,很难确定,但self.inorder(self._left)没有意义)

当您在类的某个实例instance上调用此函数时,它看起来像:

with open(...) as f:
    instance.inorder(f)

最新更新