在python3.x问题中向文件写入遍历
我试图遍历一个堆,并将遍历写入一个文件,但我失败得很惨在python3.x问题中向文件写入遍历,python,python-3.x,file-io,heap,traversal,Python,Python 3.x,File Io,Heap,Traversal,我试图遍历一个堆,并将遍历写入一个文件,但我失败得很惨 当我只想在文件中打印出节点时,我的终端会收到一个最大遍历深度的问题。我认为您的代码应该更像这样: def inorder(self, file): if self._left is not None: file.write(str(self) + ' ') self._left.inorder(file) file.write(str(self) + ' ') if self.
当我只想在文件中打印出节点时,我的终端会收到一个最大遍历深度的问题。我认为您的代码应该更像这样:
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)
请注意:
文件是一个参数,传递给递归调用,而不是每次打开ed李>
通过身份不平等测试None
;及
我假设您有一个树结构,其中self.\u left
和self.\u right
是与self
相同的类的实例(由于您提供的类太少,很难确定,self.inoder(self.\u left)
没有意义)李>
在类的某个实例instance
上调用此函数时,它将如下所示:
with open(...) as f:
instance.inorder(f)
为什么不将文件j
作为一个参数,而不是将其保持打开状态?另外,您的检查应该是不是None
@jornsharpe编辑了我的代码-它们应该是不同的文件,每个遍历一个,这不是我的意思;每次递归都要重新打开,只需在外部打开一次,然后将文件对象作为参数传入。很抱歉,恐怕我不明白。我应该将with open放在函数定义的上方?例如,def inorder(self,I):
然后用open(…)将其称为I:instance.inorder(I)