我试图遍历一个堆,并将遍历写入一个文件,但我失败了。
当我只想在文件中打印出节点时,我一直遇到最大遍历深度的问题。
我认为您的代码应该更像这样:
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)
注意:
- 要写入的
file
是一个参数,传递给递归调用,而不是每次都传递open
- 身份不平等检测
None
;以及 - 我假设您有一个树结构,其中
self._left
和self._right
与self
是同一类的实例(由于您提供的类太少,很难确定,但self.inorder(self._left)
没有意义)
当您在类的某个实例instance
上调用此函数时,它看起来像:
with open(...) as f:
instance.inorder(f)